其他分享
首页 > 其他分享> > Permutations II - LeetCode

Permutations II - LeetCode

作者:互联网

目录

题目链接

Permutations II - LeetCode

注意点

解法

解法一:因为有重复的数字所以排列的个数不确定几个,一直生成新的排列直到和原始的数列相同为止

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

小结

标签:nextPermutation,temp,nums,Permutations,ret,II,while,vector,LeetCode
来源: https://www.cnblogs.com/multhree/p/10392339.html