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 };
  • 相关阅读:
    不用加减乘除做加法
    数组中只出现一次的数字
    平衡二叉树
    二叉树的深度
    两个链表的第一个公共结点
    连续子数组的最大和
    最小的K个数
    数组中出现次数超过一半的数字
    二叉搜索树与双向链表
    复杂链表的复制
  • 原文地址:https://www.cnblogs.com/chkkch/p/2768816.html
Copyright © 2011-2022 走看看