491. 递增子序列

给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是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]。
给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。
贡献者

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Java, 18ms, 击败93%, 回溯+剪枝

class Solution {
    public List<List<Integer>> findSubsequences(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums.length < 2)
            return result;
        List<Integer> current = new ArrayList<>();
        HashSet<List<Integer>> set = new HashSet<>();
        findSubsequencesHelper(set, current, nums,0, Integer.MIN_VALUE);
        result = new ArrayList<>(set);
        return result;
    }

    public void findSubsequencesHelper(HashSet<List<Integer>> result, List<Integer> current, int[] nums,
                                       int nextIndex, int prev) {
        if (current.size() >= 2)
            result.add(new ArrayList<>(current));

        HashSet<Integer> set = new HashSet<>();         // 记录本层的情况,本层如果重复是可以剪枝的
        for (int i = nextIndex; i < nums.length; i++) {
            // 一开始想着直接在if里判断nums[i] == nums[i - 1],但这并不正确
            // 我们需要减去的是同一层的重复元素,但不同层是可以相同的
            if (nums[i] < prev || set.contains(nums[i]))
                continue;
            current.add(nums[i]);
            set.add(nums[i]);
            findSubsequencesHelper(result, current, nums,i + 1, nums[i]);
            current.remove(current.size() - 1);
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值