# 代码随想录算法训练营Day25 | Leetcode 491 非递减子序列 Leetcode 46 全排列 Leetcode 47 全排列Ⅱ

### Leetcode 491 非递减子序列

class Solution {
public:
vector<int>path;
vector<vector<int>>res;
void backtracking(vector<int> &nums,int index)
{
if(path.size()>1)
{
res.push_back(path);
}
if(index>=nums.size())
{
return;
}
unordered_set<int>used;
for(int i=index;i<nums.size();i++)
{
if(!path.empty()&&nums[i]<path.back()||(used.find(nums[i])!=used.end()))
{
continue;
}
used.insert(nums[i]);
path.push_back(nums[i]);
backtracking(nums, i+1);
path.pop_back();
}
return;

}

vector<vector<int>> findSubsequences(vector<int>& nums) {
backtracking(nums, 0);
return res;
}
};

### Leetcode 46 全排列

class Solution {
public:
vector<int>path;
vector<vector<int>>res;
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;
}
path.push_back(nums[i]);
used[i]=true;
backtracking(nums, used);
path.pop_back();
used[i]=false;

}
return;

}

vector<vector<int>> permute(vector<int>& nums) {
vector<bool>used(nums.size(),false);
backtracking(nums, used);
return res;
}
};

### Leetcode 47 全排列Ⅱ

class Solution {
public:
vector<int>path;
vector<vector<int>>res;
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 (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false)
{
continue;
}
if(used[i]==false)
{
path.push_back(nums[i]);
used[i]=true;
backtracking(nums, used);
path.pop_back();
used[i]=false;
}
}
return;
}

vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<bool>used(nums.size(),false);
backtracking(nums, used);
return res;
}
};

• 21
点赞
• 4
收藏
觉得还不错? 一键收藏
• 0
评论
02-26 436
11-29 481
01-30 1110
07-07 423
12-20 1278
02-08 329
09-04 631
09-06 605
09-04 355
09-04 373
09-06 865
09-04 1043
09-05 924
09-07 951
09-04 509
08-29 717

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。