[leetcode] 491. Increasing Subsequences

本文介绍了一种使用深度优先搜索(DFS)算法寻找整数数组中所有非减子序列的方法。给定数组长度不超过15,数值范围在[-100,100]之间,可能存在重复数字。通过递归实现的DFS算法确保了子序列长度至少为2,并利用集合避免重复解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

题目:给一个整数数组,要求找到所有非减子序列,并且每个子序列的长度至少为2。
【注意】
1. 给定数组的长度不超过15
2.整数的范围为[-100, 100]
3. 数组中可能存在重复的数字,也可以算作一个子序列。

这道题可以采用深度优先搜索的方法解决。假设使用tmp来存储当前考虑的子序列,k表示tmp中最后一个元素的下标的后一个,则如果nums[k]的元素不小于tmp中的最后一个元素,就可以将其增加到tmp中,然后继续处理k+1处的元素,直到最后一个元素或者元素比最后一个小。接着返回原始的tmp,将nums[k]弹出,继续下一次dfs。

class Solution {
public:
    vector<vector<int>> findSubsequences(vector<int>& nums) {
        set<vector<int>> res; // use set to filter same solution
        vector<int> tmp; // a solution item
        dfs(nums, res, tmp, 0);
        return vector<vector<int>> (res.begin(), res.end());
    }


    void dfs(vector<int>& nums, set<vector<int>>& res, vector<int> tmp, int k) {

        /*
            k: start index for DFS
         */

        if (tmp.size() >= 2) res.insert(tmp);

        for (int i = k; i < nums.size(); ++i) {
            // append element into tmp when it is empty 
            // or the new element is not less then the last element
            if (tmp.size() == 0 || nums[i] >= tmp.back()) {
                tmp.push_back(nums[i]);
                dfs(nums, res, tmp, i+1); //iteratively dfs among the remaining elements
                tmp.pop_back(); 
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值