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]]

需要注意的是需要去除重复的递增序列。

我之前的思路是类似动态规划的,从前往后遍历数组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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值