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]]
Note:
- The length of the given array will not exceed 15.
- The range of integer in the given array is [-100,100].
- The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.
public class Solution {
public List<List<Integer>> findSubsequences(int[] nums) {
Set<List<Integer>> res = new HashSet<List<Integer>>();
if (nums == null || nums.length < 2) {
return new ArrayList(res);
}
DFS(res, new ArrayList<Integer>(), nums, 0);
return new ArrayList(res);
}
private void DFS(Set<List<Integer>> lists, List<Integer> list, int[] nums, int start) {
if (list.size() >= 2) {
lists.add(new ArrayList(list));
}
for (int i = start; i < nums.length ; i ++) {
if (list.size() == 0 || nums[i] >= list.get(list.size() - 1)) {
list.add(nums[i]);
DFS(lists, list, nums, i + 1);
list.remove(list.size() - 1);
}
}
}
}
另一种方法设置uniquelist。代码如下:
public class Solution {
public List<List<Integer>> findSubsequences(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> cur = new ArrayList<>();
if(nums == null || nums.length <= 1) {
return res;
}
helper(nums, res, 0, cur);
return res;
}
private void helper(int[] nums, List<List<Integer>> res, int index, List<Integer> cur) {
if(cur.size() >= 2) {
res.add(new ArrayList<>(cur));
}
List<Integer> unique = new ArrayList<>();
for(int i = index; i < nums.length; i++) {
if(index > 0 && nums[i] < nums[index - 1]) {
continue;
}
if(unique.contains(nums[i])) {
continue;
}
unique.add(nums[i]);
cur.add(nums[i]);
helper(nums, res, i + 1, cur);
cur.remove(cur.size() - 1);
}
}
}