回溯算法part05 491. 非递减子序列 46. 全排列 47. 全排列 II
491. 非递减子序列
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
public:
void backTracing(vector<int>& nums,int startIndex){
if(path.size()>1) result.push_back(path);
unordered_set<int> uset;
for(int i = startIndex;i<nums.size();i++){
if( (!path.empty() && nums[i]<path.back()) || uset.find(nums[i]) != uset.end()) continue; //非递增数组或者单层元素重复,跳过该层元素
uset.insert(nums[i]); // 记录这个元素在本层用过了,本层后面不能再用了
path.push_back(nums[i]);
backTracing(nums,i+1);
path.pop_back();
}
}
vector<vector<int>> findSubsequences(vector<int>& nums) {
backTracing(nums,0);
return result;
}
};
46. 全排列
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
public:
void backtracking(vector<int>& nums,vector<int>& used){ //值得注意的是,这里面的used是深度遍历的,与491本层使用有差别,所以去重位置有区别
if(path.size()==nums.size()){
result.push_back(path);
return;
} //叶子节点回收元素
for(int i = 0; i<nums.size();i++){
if(used[i]==1) continue;
used[i] = 1;
path.push_back(nums[i]);
backtracking(nums,used);
path.pop_back();
used[i] = 0;
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<int> used(nums.size(),0);
backtracking(nums,used);
return result;
}
};
47. 全排列 II
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums,vector<int>& used){
// 此时说明找到了一组
if (path.size() == nums.size()) {
result.push_back(path);
return;
}
for(int i = 0;i<nums.size();i++){
if(i>0&&nums[i]==nums[i-1]&&used[i - 1] ==0) continue; //used[i - 1] ==0至关重要,树层上去重
if(!used[i]){
used[i] = 1;
path.push_back(nums[i]);
backtracking(nums,used);
used[i] = 0;
path.pop_back();
}
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(), nums.end()); //排序
vector<int> used(nums.size(),0);
backtracking(nums,used);
return result;
}
};