day21

ikun1111發表於2024-09-09
  1. 非遞減子序列

class Solution {
public:
void backtracking(vector &nums, int start)
{
if(path.size() > 1)
{
ret.push_back(path);
}
if(start == nums.size())
{
return;
}
unordered_set uset;
for(int i = start; 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> findSubsequences(vector& nums) {
backtracking(nums, 0);
return ret;
}
private:
vector path;
vector<vector> ret;
};

  1. 全排列

class Solution {
public:
void backtracking(vector &nums, vector &used)
{
if(path.size() == nums.size())
{
ret.push_back(path);
return;
}
for(int i = 0; i < nums.size(); ++i)
{
if(used[i] == 1)
{
continue;
}
path.push_back(nums[i]);
used[i] = 1;
backtracking(nums, used);
path.pop_back();
used[i] = 0;
}
}
vector<vector> permuteUnique(vector& nums) {
vector used(nums.size(), 0);
backtracking(nums, used);
return ret;
}
private:
vector path;
vector<vector> ret;
};
3. 全排列II

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