File tree 1 file changed +44
-0
lines changed
solution/0046.Permutations
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ private:
3
+ void my_next_permutation (vector<int >::iterator b, vector<int >::iterator e)
4
+ {
5
+ // 指针从后往前移动找到第一个下降值, (如 1, 3, 2 的1为下降值)
6
+ // 在这个下降值(1)后面找一个比下降值大的最小值(2),与下降值(1)交换
7
+ // 交换后原来下降值之后的位置做排序(2, 1, 3)
8
+ vector<int >::iterator p = e-2 ;
9
+ while (p >= b && *p > *(p+1 ))
10
+ --p ;
11
+
12
+ if (p >= b)
13
+ {
14
+ int M = *p ;
15
+ vector<int >::iterator pnindex = p ;
16
+ for (vector<int >::iterator pn = p+1 ; pn < e; ++pn)
17
+ if (*pn > *p)
18
+ {
19
+ M = min (M, *pn) ;
20
+ pnindex = pn ;
21
+ }
22
+ swap (*p, *pnindex) ;
23
+ sort (p+1 , e) ;
24
+ }
25
+ else
26
+ sort (b, e) ;
27
+ }
28
+ public:
29
+ vector<vector<int >> permute (vector<int >& nums) {
30
+ int n = nums.size () ;
31
+ int cnt = n ;
32
+ while (--n)
33
+ cnt *= n ;
34
+
35
+ vector<vector<int >> res ;
36
+ while (cnt--)
37
+ {
38
+ res.push_back (nums) ;
39
+ // next_permutation(nums.begin(), nums.end()) ;
40
+ my_next_permutation (nums.begin (), nums.end ()) ;
41
+ }
42
+ return res ;
43
+ }
44
+ };
You can’t perform that action at this time.
0 commit comments