-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIncreasingSubsequences.java
More file actions
79 lines (62 loc) · 2.42 KB
/
Copy pathIncreasingSubsequences.java
File metadata and controls
79 lines (62 loc) · 2.42 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Given an integer array, your task is to find all the different possible increasing subsequences
// of the given array, and the length of an increasing subsequence should be at least 2.
// See: https://leetcode.com/problems/increasing-subsequences/
package leetcode.backtracking;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class IncreasingSubsequences {
/**
* Simple but not very fast solution.
*/
public List<List<Integer>> findSubsequences(int[] nums) {
Set<List<Integer>> totalRes = new HashSet<>();
helper(nums, 0, new LinkedList<>(), totalRes);
return new LinkedList<List<Integer>>(totalRes);
}
private void helper(int[] nums, int start, LinkedList<Integer> currRes, Set<List<Integer>> totalRes) {
if (currRes.size() >= 2)
totalRes.add(new LinkedList<>(currRes));
for (int i = start; i < nums.length; i++) {
if (currRes.isEmpty() || currRes.peekLast() <= nums[i]) {
currRes.add(nums[i]);
helper(nums, i + 1, currRes, totalRes);
currRes.removeLast();
}
}
}
/**
* Brute force DFS solution (accepted).
* TODO: add faster solution.
*/
private Set<List<Integer>> ans = new HashSet<>();
public List<List<Integer>> findSubsequences_var1(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
LinkedList<Integer> curr = new LinkedList<>();
curr.add(nums[i]);
dfs(nums, i, curr);
}
return new LinkedList<>(ans);
}
private void dfs(int nums[], int start, LinkedList<Integer> curr) {
if (start == nums.length)
return;
if (curr.size() >= 2)
ans.add(new LinkedList<>(curr));
for (int i = start + 1; i < nums.length; i++) {
if (nums[start] <= nums[i]) {
curr.add(nums[i]);
dfs(nums, i, curr);
curr.removeLast();
}
}
}
public static void main(String[] args) {
IncreasingSubsequences sln = new IncreasingSubsequences();
System.out.println(sln.findSubsequences(new int[] { 4, 6, 7, 7 }));
//
System.out.println(sln.findSubsequences(new int[] { 4, 3, 2, 1 }));
System.out.println(sln.findSubsequences(new int[] { 1, 4, 3 }));
}
}