LeetCode-491递增子序列-中等

标题:491递增子序列-中等

题目

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

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

示例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]]

提示

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

代码Java

List<List<Integer>> ans = new ArrayList<>();
    List<Integer> temp = new ArrayList<>();

    public List<List<Integer>> findSubsequences(int[] nums) {
        if (nums == null || nums.length == 0) return ans;
        backTracking(nums, 0);
        return ans;
    }

    public void backTracking(int[] nums, int start) {
        if (temp.size() >= 2) {
            ans.add(new ArrayList<>(temp));
        }
        if (start >= nums.length) return;
        int[] used = new int[201];  // 用于记录本层 是否元素被使用
        for (int i = start; i < nums.length; i++) {
            // 层级去重       ||      深层判定
            // 层级去重 存在问题: 由于没有排序,因此两个相同的元素可能没有相邻,导致错误
            // 该用记录发存储
//            if ((i > 0 && i > start && nums[i] == nums[i - 1]) ||
//                    (!temp.isEmpty() && nums[i] < temp.get(temp.size() - 1))) {
//                continue;
//            }
            // 上面的分解,同理
//            if (i > 0 && i > start && nums[i] == nums[i - 1]) continue;
//            if (!temp.isEmpty() && nums[i] < temp.get(temp.size() - 1)) continue;

            if ((!temp.isEmpty() && nums[i] < temp.get(temp.size() - 1) )|| used[nums[i] + 100] == 1) {
                continue;
            }
            used[nums[i] + 100] = 1;
            temp.add(nums[i]);
            backTracking(nums, i + 1);
            temp.remove(temp.size() - 1);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SoaringW

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值