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

      

  • 相关阅读:
    20201107
    20201024
    20201020
    20200331
    20200330
    20200320
    20200319
    20200310
    20200221
    20190926
  • 原文地址:https://www.cnblogs.com/willwu/p/6227658.html
Copyright © 2020-2023  润新知