LeetCode491—递增子序列(java版)

题目描述:

标签:深度优先搜索

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

 代码:

 思路分析:注意和求 子集 和  去重  的区别!

1、首先不能对数组进行排序,因为排序后都是递增的序列了!

2、递归结束条件一样是,startIndex > nums.length,可以不写,因为循环里也同样判断了

3、从左到右遍历相同,是startIndex开始

4、从上到下遍历,要记得去重,去重原则是建立一个hash数组,因为-100<=nums[i]<=100,所以长度为201,记录同一层中是否使用过该数,不需要在回溯返回是设置used=0,因为这样就相当于不记得同层使用过这个数了,没达到去重效果

5、回溯结束,只需移除末尾元素

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    public List<List<Integer>> findSubsequences(int[] nums) {
        backTracing(nums,0);
        return result;
    }

    public void backTracing(int[] nums,int stratIndex){
        if(path.size() > 1){
            result.add(new ArrayList<Integer>(path));
        }
        int[] used = new int[201];
        for(int i = stratIndex;i < nums.length;i++){
            if((!path.isEmpty() && nums[i] < path.get(path.size()-1)) || used[nums[i] + 100 ] == 1){
                continue;
            }
            path.add(nums[i]);
            used[nums[i] + 100] = 1;
            backTracing(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、付费专栏及课程。

余额充值