首页 > 其他 > 详细

Permutations II

时间:2015-10-13 06:58:08      阅读:325      评论:0      收藏:0      [点我收藏+]

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 };

 

Permutations II

原文:http://www.cnblogs.com/amazingzoe/p/4873390.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!