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的思想。

    首先需要遍历输入数组,获取一共有多少种不同的数字,每个数字有多少个。 最简单的方法,排序后统计。

    然后就是对应位置填数字的游戏了,DFS即可。

     1 class Solution {
     2 public:
     3    vector<vector<int> > vi;
     4     vector<int> types;  // 数字缓存数组
     5     vector<int> counts; // 数字计数器数组
     6     vector<int> seq;    //  打印数组
     7 
     8     void generatePermute(int len)
     9     {
    10         if(len==0)
    11         {
    12             vi.push_back(seq);
    13             return;
    14         }
    15         for(int i=0;i<types.size();i++)
    16         {
    17             if((counts[i])>0)
    18             {
    19                 counts[i]--;
    20                 seq[len-1]=types[i];    //第len-1 是否存放types[i]
    21                 generatePermute(len-1);
    22                 counts[i]++;
    23             }
    24         }
    25     }
    26 
    27     vector< vector<int> > permuteUnique(vector<int> &num) {
    28         
    29         if(num.size()==0) return vi;
    30         sort(num.begin(),num.end());
    31         
    32         vi.clear();      //结果数组初始化
    33         types.clear();   //数字缓存数组初始化
    34         counts.clear();  //计数器初始化
    35         seq.resize(num.size());  //输出数组大小设定
    36 
    37         int j=0;
    38         types.push_back(num[0]);
    39         counts.push_back(1);
    40 
    41         for(int i=1;i<num.size();i++)
    42         {
    43             if(num[i]==types.back())
    44             {
    45                 counts.back()++;
    46             }
    47             else
    48             {
    49                 types.push_back(num[i]);
    50                 counts.push_back(1);
    51             }
    52         }
    53         generatePermute(num.size());
    54         return vi;
    55     }
    56 };

    转载请注明出处: http://www.cnblogs.com/double-win/ 谢谢!

  • 相关阅读:
    RM报表 实际打印的判断
    ehlib 如何用代码,选中checkbox呢?
    [CF632A]Grandma Laura and Apples
    [洛谷P3693]琪露诺的冰雪小屋
    [CF1065A]Vasya and Chocolate
    [UOJ #52]【UR #4】元旦激光炮
    [UOJ #48]【UR #3】核聚变反应强度
    [UOJ #51]【UR #4】元旦三侠的游戏
    [洛谷P1401]城市
    [洛谷P4722]【模板】最大流 加强版 / 预流推进
  • 原文地址:https://www.cnblogs.com/double-win/p/3793293.html
Copyright © 2011-2022 走看看