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;
    }
};

小结

posted @ 2019-02-17 19:29  闽A2436  阅读(124)  评论(0编辑  收藏  举报