Increasing Subsequences
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 .
Example:
Input:
[4, 6, 7, 7]
Output:
[[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
public class Solution {
public List<List<Integer>> findSubsequences(int[] nums) {
Set<List<Integer>> ans = new HashSet<>();
dfs(nums, 0, new ArrayList<>(), ans);
return new ArrayList<>(ans);
}
public void dfs(int[] nums, int start, List<Integer> sub, Set<List<Integer>> ans) {
if(sub.size() >= 2){
ans.add(new ArrayList<>(sub));
}
for(int i = start; i < nums.length; i ++) {
if(sub.size() == 0 || sub.get(sub.size() - 1) <= nums[i]) {
sub.add(nums[i]);
dfs(nums, i + 1, sub, ans);
sub.remove(sub.size() - 1);
}
}
}
}
public class Solution {
public List<List<Integer>> findSubsequences(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
dfs(nums, 0, new ArrayList<>(), ans);
return ans;
}
public void dfs(int[] nums, int start, List<Integer> sub, List<List<Integer>> ans) {
if(sub.size() >= 2){
ans.add(new ArrayList<>(sub));
}
Set<Integer> set = new HashSet<>();
for(int i = start; i < nums.length; i ++) {
if(set.contains(nums[i])) continue;
if(sub.size() == 0 || sub.get(sub.size() - 1) <= nums[i]) {
sub.add(nums[i]);
set.add(nums[i]);
dfs(nums, i + 1, sub, ans);
sub.remove(sub.size() - 1);
}
}
}
}