LeetCode-day24-非递减子序列

491. 非递减子序列

本题有几个要点

1. 要去重,但是又不能对原数组进行排序,所以需要用新的排序方法,本层使用Set,此时是不需要在回溯中移除set中的元素的,因为下一层的时候已经新建了一个Set

2. 如何保证子序列是递增的?!path.isEmpty() && nums[i] < path.get(path.size() - 1)

看下面的图,只要所取元素小于子序列的最后一个元素,就continue

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    
    public List<List<Integer>> findSubsequences(int[] nums) {
        backtrack(nums, 0);
        return res;
    }

    public void backtrack(int[] nums, int startIndex) {
        if (path.size() >= 2) {
            res.add(new ArrayList<>(path));  // 深拷贝path
        }
        Set<Integer> used = new HashSet<>();  // 用于当前层去重
        for (int i = startIndex; i < nums.length; i++) {
            if (!path.isEmpty() && nums[i] < path.get(path.size() - 1)) {
                continue;  // 保证子序列递增
            }
            if (used.contains(nums[i])) {
                continue;  // 同一层不能重复选择相同元素
            }
            used.add(nums[i]);
            path.add(nums[i]);
            backtrack(nums, i + 1);  // 递归
            path.remove(path.size() - 1);  // 回溯
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值