491. 递增子序列

描述

给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。

数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。

 

链接

491. 递增子序列 - 力扣(LeetCode) (leetcode-cn.com)

 

解法

 1 class Solution {
 2     // 定义全局变量保存结果
 3     List<List<Integer>> res = new ArrayList<>();
 4     List<Integer> path = new ArrayList<>();
 5     
 6     public List<List<Integer>> findSubsequences(int[] nums) {
 7         // idx 初始化为 0,开始 回溯(dfs 搜索)。
 8         BackTracking(nums, 0);
 9         return res;
10     }
11 
12     private void BackTracking(int[] nums, int idx) {
13         // 只要当前的递增序列长度大于 1,就加入到结果 res 中,然后继续搜索递增序列的下一个值。
14         if (path.size() > 1) {
15             res.add(new ArrayList<>(path));
16         }
17 
18         // 在 [idx , nums.length - 1] 范围内遍历搜索递增序列的下一个值。
19         // 借助 set 对 [idx, nums.length - 1] 范围内的数去重。
20         Set<Integer> set = new HashSet<>();
21         for (int i = idx; i < nums.length; i++) {
22             // 1. 如果 set 中已经有与 nums[i] 相同的值了,说明加上 nums[i] 后的所有可能的递增序列之前已经被搜过一遍了,因此停止继续搜索。
23             if (set.contains(nums[i])) { 
24                 continue;
25             }
26             set.add(nums[i]);
27             // 2. 如果 nums[i] >= nums[idx-1] 的话,说明出现了新的递增序列,因此继续 回溯搜索
28             if (idx == 0 || nums[i] >= nums[idx-1]) { // idx==0 表示开头直接纳入,不用||后的判断
29                 path.add(nums[i]);
30                 BackTracking(nums, i + 1);
31                 path.remove(path.size() - 1);
32             }
33         }
34     }
35 }

 

参考

Sweetie

posted @ 2021-12-21 10:47  DidUStudy  阅读(45)  评论(0编辑  收藏  举报