zoukankan      html  css  js  c++  java
  • [Leetcode 101] 47 Permutations II

    Problem:

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

    Analysis:

    An normal way to solve the problem is first generate all the possible permutations, and then compare it with all the existing permutations. If it's unique, then put it into the result vector. But it's too time consuming. So we should use another method.

    The method is as follows: sort the given num vector. And each time we pick a new element, if the element is duplicated, then this element cannot be picked unless it previous same element has been picked. This strategy can help us skip those situations that might cause duplication problems.

    Code:

     1 class Solution {
     2 public:
     3     vector<vector<int> > res;
     4     vector<int> t_res;
     5     int len;
     6     int *sig;
     7 
     8     vector<vector<int> > permuteUnique(vector<int> &num) {
     9         // Start typing your C/C++ solution below
    10         // DO NOT write int main() function
    11         res.clear();
    12         t_res.clear();
    13         
    14         len = num.size();
    15         sig = new int[len];
    16         for (int i=0; i<len; i++)
    17             sig[i] = 0;
    18         
    19         sort(num.begin(), num.end());
    20         
    21         dfs(0, num);
    22         
    23         return res;
    24     }
    25     
    26 private:
    27     void dfs(int l, vector<int> &num) {
    28         if (l == len) {
    29             res.push_back(t_res);
    30             return ;
    31         }
    32         
    33         for (int i=0; i<len; i++) {
    34             if (sig[i] == 0 && isValid(i, num)) {
    35                 t_res.push_back(num[i]);
    36                 sig[i] = 1;
    37                 dfs(l+1, num);
    38                 sig[i] = 0;
    39                 t_res.pop_back();
    40             }
    41         }
    42     }
    43     
    44     bool isValid(int i, vector<int> &num) {
    45         return (i==0) || (num[i-1] != num[i])|| ((num[i-1] == num[i]) && sig[i-1]);
    46     }
    47 };
    View Code
  • 相关阅读:
    yaf将错误输出打印在页面上
    yaf设置命名空间
    yaf学习资料
    在 Github 上找「好东西」的方法
    在linux命令行下执行php 程序
    linux shell脚本查找重复行/查找非重复行/去除重复行/重复行统计
    php数组函数分析--array_column
    php 去掉字符串的最后一个字符
    设置arc 的默认编辑器
    需要学习的技术
  • 原文地址:https://www.cnblogs.com/freeneng/p/3242296.html
Copyright © 2011-2022 走看看