491. 递增子序列
去重:
对同一父节点下同层的元素、、
因为不能进行排序,所以使用set进行去重,不重复的元素插入set,当当前元素在set中时,说明重复
class Solution {
public:
void backtracking(vector<int>& nums,int startIndex)
{
if(path.size()>1)
result.push_back(path);
unordered_set<int> set;
for(int i=startIndex;i<nums.size();i++)
{
//不满足条件的元素continue
if(!path.empty()&& nums[i]<path.back() || set.find(nums[i])!=set.end())
continue;
path.push_back(nums[i]);
set.insert(nums[i]);
backtracking(nums,i+1);
path.pop_back();
}
}
vector<vector<int>> findSubsequences(vector<int>& nums) {
backtracking(nums,0);
return result;
}
vector<int> path;
vector<vector<int>> result;
};
优化
使用数组进行存储
初始化数组:
int used[201] = {0};
使用过的数字置为1
class Solution {
public:
void backtracking(vector<int>& nums,int startIndex)
{
if(path.size()>1)
result.push_back(path);
int used[201] = {0};
for(int i=startIndex;i<nums.size();i++)
{
//不满足条件的元素continue
if (!path.empty() && nums[i] < path.back() || used[nums[i] + 100] == 1)
continue;
used[nums[i] + 100] = 1; // 记录这个元素在本层用过了,本层后面不能再用了
path.push_back(nums[i]);
backtracking(nums,i+1);
path.pop_back();
}
}
vector<vector<int>> findSubsequences(vector<int>& nums) {
backtracking(nums,0);
return result;
}
vector<int> path;
vector<vector<int>> result;
};