491. 非递减子序列

使用set对每层去重

 1 class Solution {
 2 public:
 3     vector<vector<int>> result;
 4     vector<int> vec;
 5     void back_tracking(const vector<int>& nums, int index){
 6         if(vec.size() >= 2){
 7             result.push_back(vec);
 8         }
 9         unordered_set<int> uset; // 使用set对本层元素进行去重
10         for(int i = index; i < nums.size(); i++){
11             if(uset.find(nums[i]) != uset.end())    continue;
12             if(vec.empty() || vec.back() <= nums[i]){
13                 uset.insert(nums[i]);
14                 vec.push_back(nums[i]);
15                 back_tracking(nums,i + 1);
16                 vec.pop_back();
17             }
18         }
19     }
20     vector<vector<int>> findSubsequences(vector<int>& nums) {
21         vector<bool> used(nums.size(),false);
22         back_tracking(nums, 0);
23         return result;
24     }
25 };

46. 全排列

利用used数组去重,每次循环在0开始

 1 class Solution {
 2 public:
 3     vector<vector<int>> result;
 4     vector<int> path;
 5     void back_tracking(const vector<int>& nums,vector<bool> used){
 6         if(path.size() == nums.size()){
 7             result.push_back(path);
 8             return;
 9         }
10         for(int i = 0; i < nums.size(); i++){
11             if(used[i])  continue;
12             path.push_back(nums[i]);
13             used[i] = true;
14             back_tracking(nums,used);
15             path.pop_back();
16             used[i] = false;
17         }
18     }
19 
20     vector<vector<int>> permute(vector<int>& nums) {
21         vector<bool> used(nums.size(),false);
22         back_tracking(nums,used);
23         return result;
24     }
25 };

47. 全排列 II

先对数组排序,然后筛选重复再回溯

 1 class Solution {
 2 public:
 3     vector<vector<int>> result;
 4     vector<int> path;
 5     void back_tracking(const vector<int>& nums, vector<bool>& used){
 6         if(path.size() == nums.size()){
 7             result.push_back(path);
 8         }
 9         for(int i = 0; i < nums.size(); i++){
10             if(used[i])    continue;
11             if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) continue;
12             used[i] = true;
13             path.push_back(nums[i]);
14             back_tracking(nums, used);
15             path.pop_back();
16             used[i] = false;
17         }
18     }
19 
20     vector<vector<int>> permuteUnique(vector<int>& nums) {
21         vector<bool> used(nums.size(),false);
22         sort(nums.begin(),nums.end());
23         back_tracking(nums, used);
24         return result;
25     }
26 };