Next Permutation - LeetCode

题目链接

Next Permutation - LeetCode

注意点

  • 如果是字典序最大的串则要返回字典序最小的串

解法

解法一:参见:http://www.cnblogs.com/grandyang/p/4428207.html 时间复杂度O(n)。

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size(),i = n-2,j = n-1;
        while(i >= 0 && nums[i] >= nums[i+1]) i--;
        cout << i;
        if(i >= 0)
        {
            while(nums[j] <= nums[i]) j--;
            swap(nums[i],nums[j]);
        }
        reverse(nums.begin()+i+1,nums.end());
    }
};

小结

  • 排列题,有许多变种

猜你喜欢

转载自www.cnblogs.com/multhree/p/10383720.html