【Leetcode之回溯】0491 递增子序列

来源:力扣(LeetCode)

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

实现语言:Java

文章记录的是第一次做力扣题时的代码,之后做题的代码放在GitHub上了,由于博客中的文章有点多,挨个修改费时费力,博客中写的有关力扣的文章和GitHub中的代码并不完全对应。力扣题GitHub地址

题目

给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是 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]]

方法:回溯

代码实现

class Solution {
    Set<List<Integer>> set = new HashSet<>();  // 用于去重重复的列表
    Stack<Integer> stack = new Stack<>();  // 存储遍历过程中的路径
    
    public List<List<Integer>> findSubsequences(int[] nums) {
        // 开始遍历的起点
        for (int i = 0; i < nums.length-1; i++) {
            stack.push(nums[i]);
            dfs(nums, i);
            stack.pop();
        }

        List<List<Integer>> res = new LinkedList<>();
        for (List<Integer> tmp: set) {
            res.add(tmp);
        }
        return res;
    }
   public void dfs(int[] nums, int index) {
       // 出口条件
        if (index >= nums.length-1) return;

        for (int i = index+1; i < nums.length; i++) {
            // 当元素的值不小于前一个元素的值时,才进行遍历
            if (nums[i] >= nums[index]) {
                stack.push(nums[i]);
                dfs(nums, i);
                // 遍历回来时输出当前栈中的元素
                set.add(new LinkedList<>(stack));
                stack.pop();
            }
        }
    }

}

执行用时:40 ms

内存消耗:53.1 MB

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值