-
Notifications
You must be signed in to change notification settings - Fork 0
/
491. 递增子序列.java
64 lines (56 loc) · 1.83 KB
/
491. 递增子序列.java
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* O(n * 2^n), S(n)
* 官解思路 (方法二):https://leetcode-cn.com/problems/increasing-subsequences/solution/di-zeng-zi-xu-lie-by-leetcode-solution/
*/
class Solution {
List<Integer> temp = new ArrayList<Integer>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
public List<List<Integer>> findSubsequences(int[] nums) {
dfs(0, Integer.MIN_VALUE, nums);
return ans;
}
public void dfs(int cur, int last, int[] nums) {
if (cur == nums.length) {
if (temp.size() >= 2) {
ans.add(new ArrayList<Integer>(temp));
}
return;
}
if (nums[cur] >= last) {
temp.add(nums[cur]);
dfs(cur + 1, nums[cur], nums);
temp.remove(temp.size() - 1);
}
if (nums[cur] != last) {
dfs(cur + 1, last, nums);
}
}
}
/**
* 自己的思路
* O(n * 2^n), S(n * 2^n)
*/
class Solution {
public List<List<Integer>> findSubsequences(int[] nums) {
Set<List<Integer>> res = new HashSet<>(); // 为了去重
// List<List<Integer>> res = new LinkedList<>();
dfsBackTrack(nums, 0, new LinkedList<>(), res);
return new LinkedList(res);
}
private void dfsBackTrack(int[] nums, int depth, List<Integer> subList, Set<List<Integer>> res){
if(nums.length == depth){
if(subList.size() >= 2){
res.add(new LinkedList<>(subList));
}
return;
}
// 不选当前数
dfsBackTrack(nums, depth + 1, subList, res);
// 选择当前数
if(subList.size() == 0 || subList.get(subList.size() - 1) <= nums[depth]){
subList.add(nums[depth]);
dfsBackTrack(nums, depth + 1, subList, res);
subList.remove(subList.size() - 1);
}
}
}