1 class Solution 
 2 {
 3 public:
 4     vector<vector<int>> permuteUnique(vector<int>& nums) 
 5     {
 6         vector<vector<int>> res;
 7         sort(nums.begin(),nums.end());
 8         helper(res,nums,0);
 9         return res;
10     }
11     
12     void helper(vector<vector<int>> &res,vector<int> nums,int beg)
13     {
14         int sz=nums.size();
15         if(beg==sz-1)
16         {
17             res.push_back(nums);
18             return ;
19         }
20         else
21         {
22             for(int i=beg;i<sz;i++)
23             {
24                 if(i!=beg&&nums[i]==nums[beg])
25                     continue;
26                 else
27                 {
28                     swap(nums[i],nums[beg]);
29                     helper(res,nums,beg+1);
30                 }
31                 
32             }
33         }
34     }
35 };

这里有个要注意的问题,不能nums的引用,因为这里要原nums序列来确定元素是否是重复元素

 

还有个使用set的方法

 1 class Solution {
 2 public:
 3     vector<string> permutation(string s) {
 4         vector<string> res;
 5         back_track(s, 0, res);
 6         return res;
 7     }
 8 
 9     void back_track(string &s, int pos, vector<string> &res){
10         if(pos == s.length()-1){
11             res.push_back(s);
12             return;
13         }
14         unordered_set<char> sc;
15         for(int i=pos;i<s.length();i++){
16             if(sc.find(s[i]) != sc.end())
17                 continue;
18             sc.insert(s[i]);
19             swap(s[i], s[pos]);
20             back_track(s, pos+1, res);
21             swap(s[i], s[pos]);
22         }
23     }
24 };

这个运行速度要慢一些

 

posted on 2018-07-10 18:55  高数考了59  阅读(79)  评论(0)    收藏  举报