Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.spa
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).code
The replacement must be in-place, do not allocate extra memory.blog
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1排序
分析了一下,得出有如下規律,accepted。大致思路和網上同樣。紅色部分是網上的解法。it
1. 從右往左掃,找到第一個不符合num[i]>=num[i+1]的數;io
2. 而後從[i+1...n-1]中找到比num[i]大的最小數num[j];這裏我直接找大於num[i]的最小值了;其實由於[i+1..n-1]是遞減的,能夠從右往左掃,找到第一個數就退出就好了。class
3. 交換num[j]和num[i];交換以後,仍然會保證[i+1...n-1]是遞減的。重構
4. 對[i+1...n-1]進行排序;由於[i+1...n-1]是遞減的,直接reverse就能夠了,不須要排序。 call
5. 若是找到的數i<0,也就是整個序列都是遞減的,那麼直接排序就行;一樣能夠用reverse。next
1 class Solution { 2 public: 3 void nextPermutation(vector<int> &num) { 4 int i; 5 for (i = num.size() - 2; i >= 0; --i) { 6 if (num[i] >= num[i + 1]) continue; 7 int minIndex = i + 1; 8 for (int j = i + 1; j < num.size(); ++j) { 9 if (num[j] > num[i] && num[j] < num[minIndex]) minIndex = j; 10 } 11 swap(num[i], num[minIndex]); 12 sort(num.begin() + i + 1, num.end()); 13 break; 14 } 15 if (i < 0) sort(num.begin(), num.end()); 16 } 17 };
不過由於能夠不用寫reverse的代碼,直接用sort看起來簡潔得多。重構了一下代碼就是:
1 class Solution { 2 public: 3 void nextPermutation(vector<int> &num) { 4 int i, j; 5 for (i = num.size() - 2; i >= 0 && num[i] >= num[i + 1]; --i); 6 if (i >= 0) { 7 for (j = num.size() - 1; j > i && num[j] <= num[i]; --j); 8 swap(num[i], num[j]); 9 } 10 sort(num.begin() + i + 1, num.end()); 11 } 12 };