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]]
需要注意的是需要去除重复的递增序列。
我之前的思路是类似动态规划的,从前往后遍历数组num元素,每个位置都对应着一个数组a,记录该位置之前所有的无重复递增子序列,当到index为i的位置的时候,只需要遍历index为i-1的数组a,如果num[i]>=a[now],那么就把这个序列加入index为i的数组a中,同时还要判断是否重复。这样查重是非常消耗时间的,故不通过。
其实这道题最头疼的无非是如何去除重复的序列,如果采取的是深度优先遍历的思想,那么就是在dfs每一层的时候不允许有重复元素出现,我们可以用一个map来保存每一层元素出现的信息,只要没有出现过都可以加到当前的now序列中去。
class Solution {
public:
void search(vector<int>& nums,int index,vector<int>& now,vector<vector<int>>& result)
{
if(now.size()>1)
result.push_back(now);
map<int,int> tmp;
for(int i=index;i<nums.size();i++)
{
if(now.size() == 0)
{
if(tmp.find(nums[i]) == tmp.end())
{
now.push_back(nums[i]);
search(nums,i+1,now,result);
now.erase(now.end()-1);
}
tmp[nums[i]]=1;
}
else
{
int pp=now.size()-1;
if(tmp.find(nums[i]) == tmp.end())
{
if(nums[i]>=now[pp])
{
now.push_back(nums[i]);
search(nums,i+1,now,result);
now.erase(now.end()-1);
}
}
tmp[nums[i]]=1;
}
}
}
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<vector<int>> result;
int n=nums.size();
if(!n)
return result;
vector<int> now;
search(nums,0,now,result);
return result;
}
};