題目:
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.
思路:
這是一個典型的深搜問題,遍歷到最後的結點時,回溯。
C++ Codes:
class Solution{
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<vector<int>> res;
vector<int> tmp;
tmp.clear();
dfs(res,nums,tmp,0);
return res;
}
void dfs(vector<vector<int>>& res, vector<int>& nums, vector<int>& tmp, int index)
{
if(tmp.size()>=2)
res.push_back(tmp);
unordered_set<int> s; //基於hash的無序集合,訪問速度更快
for(int i=index;i<nums.size();i++)
{
if((tmp.empty()||tmp.back()<=nums[i])&&s.find(nums[i]) == s.end()) //nums[i]不在s中,返回s.end()
{
tmp.push_back(nums[i]);
dfs(res,nums,tmp,i+1);
tmp.pop_back(); //回溯
s.insert(nums[i]); //將nums[i]加入到s中
}
}
}
};