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

 

posted @ 2015-10-13 04:25  amazingzoe  阅读(155)  评论(0编辑  收藏  举报