前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >​LeetCode刷题实战491:递增子序列

​LeetCode刷题实战491:递增子序列

作者头像
程序员小猿
发布2022-03-03 15:45:35
2380
发布2022-03-03 15:45:35
举报
文章被收录于专栏:程序IT圈

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 递增子序列,我们先来看题面:

https://leetcode-cn.com/problems/increasing-subsequences/

Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order.

The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.

给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。

数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。

示例

代码语言:javascript
复制
示例 1:

输入:nums = [4,6,7,7]
输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]

示例 2:

输入:nums = [4,4,3,2,1]
输出:[[4,4]]

解题

https://www.cnblogs.com/kexinxin/p/10372504.html

利用递归的思想,维护一个栈,将每次找到的比当前栈顶大的数,然后入栈,将更新过后的栈扔进递归函数,然后更新查找的初始位置即从当前的位置后一个位置开始查找。递归函数结束后,取出栈顶,进入下个循环,这样将所有元素都作为栈底元素遍历一遍。

代码语言:javascript
复制
public class Solution {
    public List<List<Integer>> findSubsequences(int[] nums) {
        Set<List<Integer>> res = new HashSet<List<Integer>>();
        helper(res, new ArrayList<Integer>(), nums, 0);
        return new ArrayList<List<Integer>>(res);
    }

    private void helper(Set<List<Integer>> res, List<Integer> subList, int[] nums, int start) {
        if (subList.size() >= 2) {
            res.add(new ArrayList<Integer>(subList));
        }
        for (int i = start; i < nums.length; i++) {
            if (subList.size() == 0 || subList.get(subList.size() - 1) <= nums[i]) {
                subList.add(nums[i]);
                helper(res, subList, nums, i + 1);
                subList.remove(subList.size() - 1);
            }
        }
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-480题汇总,希望对你有点帮助!

LeetCode刷题实战481:神奇字符串

LeetCode刷题实战482:密钥格式化

LeetCode刷题实战483:最小好进制

LeetCode刷题实战484:寻找排列

LeetCode刷题实战485:最大连续 1 的个数

LeetCode刷题实战486:预测赢家

LeetCode刷题实战487:最大连续1的个数 II

LeetCode刷题实战488:祖玛游戏

LeetCode刷题实战489:扫地机器人

LeetCode刷题实战490:迷宫

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-01-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员小猿 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 示例
  • 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档