LeetCode 491. Increasing Subsequences

LeetCode 491. Increasing Subsequences (递增子序列)

题目

链接

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

问题描述

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

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

示例

输入: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]]

提示

1 <= nums.length <= 15
-100 <= nums[i] <= 100

思路

这里是对每一层选择,就是其中的for循环,需要考虑到重复,比如1123,我取了第一个1,就已经有了123,没必要用第二个1再来一个123,这里用hashmap来存放。

复杂度分析

时间复杂度 O(n2)
空间复杂度 O(n)

代码

Java

    List<List<Integer>> ans = new LinkedList<>();
    LinkedList<Integer> path = new LinkedList<>();

    public List<List<Integer>> findSubsequences(int[] nums) {
        trace(nums, 0, -102);
        return ans;
    }

    public void trace(int[] nums, int index, int tag) {
        if (path.size() >= 2) {
            ans.add(new LinkedList(path));
        }
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = index; i < nums.length; i++) {
            if (nums[i] < tag || map.getOrDefault(nums[i], 0) >= 1) {
                continue;
            }
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
            path.add(nums[i]);
            trace(nums, i + 1, nums[i]);
            path.removeLast();
        }
    }
posted @   cheng102e  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
点击右上角即可分享
微信分享提示