zoukankan      html  css  js  c++  java
  • [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].

    先对数组进行排序,这样在DFS的时候,可以先判断前面的一个数是否和自己相等,相等的时候则前面的数必须使用了,自己才能使用,这样就不会产生重复的排列了。

     1 class Solution {
     2 private:
     3     bool canUse[100];
     4     int a[100];
     5     vector<vector<int> > ret;
     6 public:
     7     void dfs(int dep, int maxDep, vector<int> &num)
     8     {
     9         if (dep == maxDep)
    10         {
    11             vector<int> ans;
    12             for(int i = 0; i < maxDep; i++)
    13                 ans.push_back(a[i]);
    14             ret.push_back(ans);
    15             return;
    16         }
    17         
    18         for(int i = 0; i < maxDep; i++)
    19             if (canUse[i])
    20             {
    21                 if (i != 0 && num[i] == num[i-1] && canUse[i-1])
    22                     continue;
    23                     
    24                 canUse[i] = false;
    25                 a[dep] = num[i];
    26                 dfs(dep + 1, maxDep, num);
    27                 canUse[i] = true;
    28             }
    29     }
    30     
    31     vector<vector<int> > permuteUnique(vector<int> &num) {
    32         // Start typing your C/C++ solution below
    33         // DO NOT write int main() function
    34         sort(num.begin(), num.end());
    35         memset(canUse, true, sizeof(canUse));
    36         ret.clear();
    37         dfs(0, num.size(), num);
    38         return ret;
    39     }
    40 };
  • 相关阅读:
    还能这样偷懒?用Python实现网站自动签到脚本
    普通爬虫 VS 多线程爬虫!Python爬虫运行时间对比
    中文文献阅读方法及笔记模板
    约束
    可迭代对象补充
    练习题及补充
    内置函数的补充/super/异常值处理
    特殊成员
    嵌套
    面向对象知识点总结补充
  • 原文地址:https://www.cnblogs.com/chkkch/p/2768816.html
Copyright © 2011-2022 走看看