LEETCODE: 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], and [2,1,1].

还是采用递归吧,下面两种其实很类似。区别在于一个先排序,另一个是不排序。两个稍微有点差异,不过区别不大。全排列用递归的思路似乎就是如此。不过从给出的运行时间看,应该还有非递归的方式。


class Solution {
public:
    void permuteUniqueInternal(vector<int> num, int index, vector<int>& currecord, vector<vector<int>> &results) {
        if(index == num.size()) {
            results.push_back(currecord);
        }
        else {
            for(int ii = index; ii < num.size(); ii ++) {
                if(ii > index && num[ii] == num[index]) { // Do not process the same number
                    continue;
                }
                
                swap(num[index], num[ii]);
                currecord.push_back(num[index]);
                permuteUniqueInternal(num, index + 1, currecord, results);
                currecord.pop_back();
            }
            
            //sort(num.begin() + index, num.end());
        }
    }

    vector<vector<int> > permuteUnique(vector<int> &num) {
        vector<vector<int> > results;
        vector<int> currentrecord;
        sort(num.begin(), num.end());
        permuteUniqueInternal(num, 0, currentrecord, results);
        return results;
    }
};


class Solution {
public:
   bool find(vector<int> &num, int start, int end, int target)
   {
      for(int i = start; i < end; i++)
         if(num[i] == target)
            return true;
      return false;
   }

   void findAllPermute(vector<int> &num, int index, vector<int> result, vector<vector<int> >& results)
   {
      if (num.size() == index)
      {
         results.push_back(result);
         return;
      }

      for (int ii = index; ii < num.size() ; ii ++)
      {
         if(ii == index || !find(num, index, ii, num[ii]))
         {
            swap(num[index], num[ii]);
            result.push_back(num[index]);
            findAllPermute(num, index + 1, result, results);
            result.pop_back();
            swap(num[index], num[ii]);
         }

      }
   }

   vector<vector<int> > permuteUnique(vector<int> &num) {
      vector<vector<int> > results;
      vector<int> result;
      findAllPermute(num, 0, result, results);
      return results;
   }
   
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值