491. Increasing Subsequences
Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2 .
Example:
Input: [4, 6, 7, 7]
Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
Note:
- The length of the given array will not exceed 15.
- The range of integer in the given array is [-100,100].
- The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.
代码
class Solution {
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<vector<int>> res;
vector<int> tmp;
dfs(nums, 0, tmp, res);
return res;
}
void dfs(vector<int>& nums, int begin, vector<int> &tmp, vector<vector<int>> &res){
if(tmp.size()>=2){
res.push_back(tmp);
}
unordered_set<int> cache;
for(int i=begin; i<nums.size(); ++i){
if(tmp.empty() || nums[i]>=tmp.back()){
if(cache.count(nums[i])!=0) continue;
cache.insert(nums[i]);
tmp.push_back(nums[i]);
dfs(nums, i+1, tmp, res);
tmp.pop_back();
}
}
}
};
本文介绍了一种算法,用于找出给定整数数组中所有不同的递增子序列,且子序列长度至少为2。通过深度优先搜索实现,考虑了数组可能包含重复元素的情况。

2万+

被折叠的 条评论
为什么被折叠?



