491.递增子序列
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums,int startindex){
if(path.size()>=2){
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]);
backtracking(nums,i+1);
path.pop_back();
}
}
vector<vector<int>> findSubsequences(vector<int>& nums) {
backtracking(nums,0);
return result;
}
};
46.全排列
![](https://i-blog.csdnimg.cn/blog_migrate/2270023846da03fcbea382646debf8d4.png)
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums,unordered_map<int,bool>& map){
if(path.size()==nums.size()){
result.push_back(path);
return;
}
for(int i=0;i<nums.size();i++){
if(map[nums[i]]==false){
path.push_back(nums[i]);
map[nums[i]]=true;
backtracking(nums,map);
path.pop_back();
map[nums[i]]=false;
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
unordered_map<int,bool> map;
for(int i=0;i<nums.size();i++){
map[nums[i]]=false;
}
backtracking(nums,map);
return result;
}
};
47.全排列 II
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums,vector<bool> uesd){
if(nums.size()==path.size()){
result.push_back(path);
return;
}
for(int i=0;i<nums.size();i++){
if(i>=1&&uesd[i-1]==false&&nums[i]==nums[i-1]){
continue;
}
if(uesd[i]==false){
path.push_back(nums[i]);
uesd[i] = true;
backtracking(nums,uesd);
path.pop_back();
uesd[i] = false;
}
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<bool> uesd(nums.size(),false);
sort(nums.begin(),nums.end());
backtracking(nums,uesd);
return result;
}
};