递增子序列

491. 递增子序列

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

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

示例 1:

1
2
输入:nums = [4,6,7,7]
输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]

示例 2:

1
2
输入:nums = [4,4,3,2,1]
输出:[[4,4]]

提示:

  • 1 <= nums.length <= 15
  • -100 <= nums[i] <= 100

解题思路

此题需要对重复的元素去重,在同一层中使用过的元素用set进行记录

而同一树枝上的元素不需要去重,因为4,7,7这个集合是可取的,4,7和4,7重复只会出现在同一层

由于初始序列是规定好的,不能使用排序进行去重,因此只能使用set去重

image-20230824140035621

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();

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

public void traversal(int[] nums, int index){
if(path.size() >= 2){
ans.add(new ArrayList<>(path));
}
if(index == nums.length){
return;
}

Set<Integer> set = new HashSet<>();//记录同一层的数是否使用过

for(int i = index; i < nums.length; i++){
if(set.contains(nums[i])){
continue;
}
if(!path.isEmpty() && nums[i] < path.get(path.size()-1)){
continue;
}
path.add(nums[i]);
set.add(nums[i]);
traversal(nums, i+1);
path.remove(path.size()-1);

}
}
}

递增子序列
http://example.com/2023/05/05/算法/回溯/10. 递增子序列/
作者
PALE13
发布于
2023年5月5日
许可协议