码迷,mamicode.com
首页 > 其他好文 > 详细

Permutations II

时间:2016-12-27 23:29:38      阅读:418      评论:0      收藏:0      [点我收藏+]

标签:uniq   int   ssi   collect   range   bool   possible   example   follow   

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

标签:uniq   int   ssi   collect   range   bool   possible   example   follow   

原文地址:http://www.cnblogs.com/willwu/p/6227658.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!