[leetCode]491. 递增子序列

题目

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

给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。

示例:

输入: [4, 6, 7, 7]
输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
说明:

给定数组的长度不会超过15。
数组中的整数范围是 [-100,100]。
给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。

回溯

这题也是使用回溯法求解,相比第90题.子集II,这题需要得到所有的递增子集,而第90题中是将数组排序后达到对树同一层元素去重的目的,本题中不能使用这种方法,而应使用Set容器。当当前元素小于路径path集合中最后一个元素是说明子集不是递增的,所以也应该跳过选取:

class Solution {

    private List<List<Integer>> result = new ArrayList<>();
    private List<Integer> path = new ArrayList<>();

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

    private void backTracking(int[] nums, int startIndex) {
        if (path.size() > 1) { // 递增子序列长度至少为2
            result.add(new ArrayList<>(path));
        }
        Set<Integer> set = new HashSet<>(); // 对本层元素去重
        for (int i = startIndex; i < nums.length; i++) {
            if (!path.isEmpty() && nums[i] < path.get(path.size() - 1) 
            || set.contains(nums[i])) continue;
            set.add(nums[i]);
            path.add(nums[i]);
            backTracking(nums, i+1);
            path.remove(path.size() - 1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值