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/ 谢谢!

  • 相关阅读:
    Bellman-Ford(BF)和Floyd算法
    Dijkstra实现最短路径
    【图论】连通分量个数(并查集)
    【模拟】n a^o7 !
    【图论】最小生成树
    【搜索DFS】图的深度遍历(dfs)
    【搜索BFS】poj3278--Catch That Cow(bfs)
    【图论】判断给定图是否存在合法拓扑序列
    二叉排序树
    【树】判断给定森林中有多少棵树(简单做法)
  • 原文地址:https://www.cnblogs.com/double-win/p/3793293.html
Copyright © 2011-2022 走看看