• [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].

     题意:当数列中有重复数字时,求其全排列。

    思路:和permutation一样。以[1,1,2]为例,以第一个1为开始,得到[1,1,2],[1,2,1],。因为排列是将顺序的,所以我们以第二1开始时,若是不去重,则得到的和以第一个1开始时一样,所以,这时,我们要跳过那些和前面相同的数字。这时,我们应该先对数列进行排序,然后,在向中间变量存入数字的时候,若此次遍历中,前面的没有访问过,跳过即可。参看了Grandyang的博客。代码如下:

     1 class Solution {
     2 public:
     3     vector<vector<int> > permuteUnique(vector<int> &num) 
     4     {
     5         vector<vector<int>> res;
     6         vector<int> tempValue;
     7         vector<int> visited(num.size(),0);
     8         sort(num.begin(),num.end());        //对其进行排序
     9         helper(num,0,visited, tempValue,res); 
    10         return res;  
    11     }
    12 
    13     void helper(vector<int> &num,int level,vector<int> visited, vector<int> &tempValue,
    14          vector<vector<int>> &res)
    15     {
    16         if(level==num.size())
    17             res.push_back(tempValue);
    18         else
    19         {
    20             for(int i=0;i<num.size();++i)   //这里i=0
    21             {
    22                 if(i>0&&num[i]==num[i-1]&&visited[i-1]==0)  //在下一个if内也行
    23                     continue;
    24                 if(visited[i]==0)
    25                 {                   
    26                     visited[i]=1;
    27                     tempValue.push_back(num[i]);
    28                     helper(num,level+1,visited,tempValue,res);
    29                     tempValue.pop_back();
    30                     visited[i]=0;
    31                 }               
    32             }
    33         }    
    34     }
    35 };
  • 相关阅读:
    【原创】Java与数据结构(上篇:排序算法)
    【九度OJ】题目1084:整数拆分
    kaixin001接入
    Facebook接入(下)
    svn手册摘录
    Facebook接入(上)
    使用mysqldb从数据库中导出xml
    使用cmd模块,让脚本更舒服些
    django 的简单测试
    python字符串替换
  • 原文地址:https://www.cnblogs.com/love-yh/p/7206478.html
Copyright © 2020-2023  润新知