zoukankan      html  css  js  c++  java
  • 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].

    Runtime: 28ms

     1 class Solution {
     2 public:
     3     vector<vector<int>> permuteUnique(vector<int>& nums) {
     4         vector<vector<int> > result;
     5         if(nums.empty()) return result;
     6         
     7         helper(result, nums, 0, nums.size() - 1);
     8         return result;
     9     }
    10     
    11     void helper(vector<vector<int> >& result, vector<int>& nums, int depth, int n){
    12         if(depth == n){
    13             result.push_back(nums);
    14             return;
    15         }
    16         
    17         for(int i = depth; i < nums.size(); i++){
    18             if(noSwap(nums, depth, i)) continue;
    19             
    20             swap(nums[depth], nums[i]);
    21             helper(result, nums, depth + 1, n);
    22             swap(nums[depth], nums[i]);
    23         }
    24     }
    25     
    26     bool noSwap(vector<int>& nums, int depth, int i){
    27         for(int j = depth; j < i; j++){
    28             if(nums[j] == nums[i])
    29                 return true;
    30         }
    31         return false;
    32     }
    33 };
  • 相关阅读:
    [那些你所不知道的鬼畜写法]数据结构小探
    索引
    数据类型
    存储引擎
    事务
    视图、触发器、存储过程、自定义函数
    约束
    数据库介绍
    线程基础、线程池
    操作系统基础
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4873390.html
Copyright © 2011-2022 走看看