LeetCode题解(Week 4):491. Increasing Subsequences

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:

  1. The length of the given array will not exceed 15.
  2. The range of integer in the given array is [-100,100].
  3. The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.

中文大意

给定一个整形数组,找出其中的所有长度大于2的不减子序列。

题解

这道题的难点有两个,一个是找到数组中所有的不减子序列,另外一个是找到这个将找到的不减子序列进行去重处理。对于第二个难点,可通过STL中的set来解决。对于第一个难点,则通过DFS的方式进行遍历。

假设数组长度为n,当前遍历到第i个元素(i初始化为0),当前的序列为vec(初始化为空),对于原数组在i之后的元素,我们要做的是判断每一个i之后的元素是否比vec要大(或者vec为空),如果是的话,将它加到vec中,i就等于这个元素的下标,进行递归。

每当vec发生了变化,并且vec的长度大于1,就可以放到set中。

最终的代码如下:

class Solution {
public:

    void recursive(vector<int>& nums,vector<int> currvec,int currpos,set<vector<int>>& res)
    {
        //首先判断当前的vector是否应该插入到set中
        if(currvec.size()>=2&&!res.count(currvec)) 
            res.insert(currvec);

        for(int i = currpos; i < nums.size(); i++)
        {
            vector<int> nextvec = currvec;
            //如果当前的子序列为空,或者子序列中最后一个元素不大于当前遍历到的元素,就往这个子序列插入,继续递归
            if(currvec.empty()||nums[i]>=currvec.back())
            {
                nextvec.push_back(nums[i]);
                recursive(nums,nextvec,i+1,res);
            }
        }
    }

    vector<vector<int>> findSubsequences(vector<int>& nums) 
    {
        set<vector<int>> res;

        if(!nums.size()) return vector<vector<int>>();
        vector<int> currvec;
        recursive(nums,currvec,0,res);

        //将set转化为vector输出
        vector<vector<int>> resultvec(res.begin(), res.end());

        return resultvec;
    }
};

复杂度分析

这道题需要用到一个辅助的数组,来对当前的状态进行存储,因此算法的空间复杂度为O(n),而在时间复杂度方面,由于每一次对i之后的元素都进行判断,因此时间复杂度为O(n-1 + n-2 + … + 1) = O(n^2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值