leetcode个人题解——#31 Next Permutation

写这题时脑子比较混乱,重写了一遍wiki大佬的解法。

算法:

According to Wikipedia, a man named Narayana Pandita presented the following simple algorithm to solve this problem in the 14th century.

  1. Find the largest index k such that nums[k] < nums[k + 1]. If no such index exists, just reverse nums and done.
  2. Find the largest index l > k such that nums[k] < nums[l].
  3. Swap nums[k] and nums[l].
  4. 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());
    }
};

 

上一篇:● firewalld.service Loaded: not-found (Reason: No such file or directory)


下一篇:[Errno 2] No such file or directory