491.递增子序列
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int>& nums, int start){
if(path.size() >= 2){
res.push_back(path); //要取树上所有节点 所以不加return
}
unordered_set<int> myset; // 使用set对本层元素进行去重
for(int i = start; i < nums.size(); i++){
if(myset.find(nums[i]) != myset.end()) continue;
myset.insert(nums[i]); //往集合里面添加元素
if(path.size() == 0 || path[path.size() - 1] <= nums[i]){
path.push_back(nums[i]);
backtracking(nums, i+1);
path.pop_back();
}
}
}
vector<vector<int>> findSubsequences(vector<int>& nums) {
backtracking(nums, 0);
return res;
}
};
46.全排列
排列 要用到used 不需要index ,i从0开始
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int>& nums, vector<bool>& used){
if(path.size() == nums.size()){
res.push_back(path);
return;
}
for(int i = 0; i < nums.size(); i++){
if(used[i] == true) continue;
used[i] = true;
path.push_back(nums[i]);
backtracking(nums, used);
path.pop_back();
used[i] = false;
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<bool> used(nums.size(), 0);
backtracking(nums, used);
return res;
}
};
47.全排列 II
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int>& nums, vector<bool>& used){
if(path.size() == nums.size()){
res.push_back(path);
return;
}
for(int i = 0; i < nums.size(); i++){
if(used[i] == true) continue;
// used[i - 1] == true,说明同一树枝nums[i - 1]使用过
// used[i - 1] == false,说明同一树层nums[i - 1]使用过
// 如果同一树层nums[i - 1]使用过则直接跳过
if(i > 0 && nums[i - 1] == nums[i] && used[i - 1] == false) continue;
used[i] = true;
path.push_back(nums[i]);
backtracking(nums, used);
path.pop_back();
used[i] = false;
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
//去重需要给数组排序
sort(nums.begin(), nums.end());
vector<bool> used(nums.size(), 0);
backtracking(nums, used);
return res;
}
};