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 @ 2022-06-14 18:18  cheng102e  阅读(22)  评论(0编辑  收藏  举报