File tree Expand file tree Collapse file tree 1 file changed +44
-9
lines changed Expand file tree Collapse file tree 1 file changed +44
-9
lines changed Original file line number Diff line number Diff line change 2222**********************************************************************************/
2323
2424/*
25- 1 2 3 4
26- 1 2 4 3
27- 1 3 2 4
28- 1 3 4 2
29- 1 4 2 3
30- 1 4 3 2
31- 2 1 3 4
32- ...
33- */
25+ * Take a look the following continuous permutation, can you find the patern?
26+ *
27+ * 1 2 3 4
28+ * 1 2 4 3
29+ * 1 3 2 4
30+ * 1 3 4 2
31+ * 1 4 2 3
32+ * 1 4 3 2
33+ * 2 1 3 4
34+ * ...
35+ *
36+ * The pattern as below:
37+ *
38+ * 1) find the first place which num[i-1] < num[i]
39+ * 2) find the first number from n-1 to i which >= num[i-1]
40+ * 3) swap the 2) num with num[i-1]
41+ * 4) sort the sub-array [i, n) //actuall sort is fine as well
42+ *
43+ * For example:
44+ *
45+ * 1 4 3 2 <-- 1) find the first place which num[i-1] < num[i]
46+ * ^
47+ *
48+ * 1 4 3 2 <-- 2) find the first number from n-1 to i which >= num[i-1]
49+ * ^ ^
50+ *
51+ * 2 4 3 1 <-- 3) swap them
52+ * ^ ^
53+ *
54+ * 2 4 3 1 <-- 4) sort
55+ * ^ ^
56+ *
57+ * 2 1 3 4
58+ *
59+ * Edge Case:
60+ *
61+ * 4 3 2 1, the next permutation is 1 2 3 4
62+ */
3463
3564#include < stdio.h>
3665#include < stdlib.h>
4069#include < algorithm>
4170using namespace std ;
4271
72+
4373void nextPermutation (vector<int > &num) {
4474
4575 if (num.size ()<=1 ) return ;
@@ -54,10 +84,15 @@ void nextPermutation(vector<int> &num) {
5484 int tmp = num[j];
5585 num[j] = num[i-1 ];
5686 num[i-1 ] = tmp;
87+ // sort works as well
88+ // sort(num.begin()+i, num.end());
5789 reverse (num.begin ()+i, num.end ());
5890 return ;
5991 }
92+ // edge case: 4 3 2 1
6093 if (i == 1 ){
94+ // sort works as well
95+ // sort(num.begin(), num.end());
6196 reverse (num.begin (), num.end ());
6297 return ;
6398 }
You can’t perform that action at this time.
0 commit comments