Permutations II

Posted Will Wu的学习笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Permutations II相关的知识,希望对你有一定的参考价值。

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

分析: 全组合的思想,保证start和end之间交换的时候中间没有与end相同的数字

class Solution {
public:
   void swap(int i, int j, vector<int>& nums){
        int temp =nums[i];
        nums[i] = nums[j];
        nums[j]= temp;
    }
    bool isSwap(int start, int end, vector<int>& nums){
        for(; start<end; start++)
            if(nums[start] == nums[end])
                return false;
        return true;
    }
    
    void allRange(int start, vector<int>& nums, vector<vector<int>>& res)
    {
        if(start==nums.size()-1)
            return;
        for(int i =start; i<nums.size(); i++){
           if(isSwap(start,i,nums))
           {
               swap(start, i, nums);
                if(start!=i)
                    res.push_back(nums);
                allRange(start+1, nums, res);
                swap(i, start, nums);
           }
            
        }
    }
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int>> res;
        if(nums.size()==0)
            return res;
        res.push_back(nums);
        allRange(0, nums, res);
        return res;
    }
};

  

以上是关于Permutations II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-Permutations II-47

[Lintcode]16. Permutations II/[Leetcode]47. Permutations II

LeetCode46,47 Permutations, Permutations II

leetcode 46-Permutations and 47-Permutations II

[Leetcode] Permutations II

LintCode : Permutations II