写这题时脑子比较混乱,重写了一遍wiki大佬的解法。
算法:
According to Wikipedia, a man named Narayana Pandita presented the following simple algorithm to solve this problem in the 14th century.
- Find the largest index
k
such thatnums[k] < nums[k + 1]
. If no such index exists, just reversenums
and done. - Find the largest index
l > k
such thatnums[k] < nums[l]
. - Swap
nums[k]
andnums[l]
. - Reverse the sub-array
nums[k + 1:]
class Solution { public: void nextPermutation(vector<int>& nums) { int max; int min; for(max = nums.size() - 2; max >= 0; max--) if(nums[max] < nums[max+1]) break; if(max < 0){ reverse(nums.begin(),nums.end()); return; } else for(min = nums.size() - 1; min > 0; min--) if(nums[min] > nums[max]) break; swap(nums[min], nums[max]); reverse(nums.begin() + max + 1, nums.end()); } };