Description
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.
Solution
给一个整数数组,找到这个数组中所有的递增子序列。
Using a helper function to recursively find all the subsequence. If the subquence’s length is longer than 1, add it into result list. Then use a for loop to find subsequences. A hash set is used to avoid duplicate circumstance.
Code
class Solution {
private List<List<Integer>> res;
public List<List<Integer>> findSubsequences(int[] nums) {
res = new ArrayList<>();
helper(new LinkedList<Integer>(), 0, nums);
return res;
}
private void helper(LinkedList<Integer> sequence, int index, int[] nums){
if (sequence.size() > 1){
res.add(new LinkedList<Integer>(sequence));
}
Set<Integer> used = new HashSet<>();
for (int i = index; i < nums.length; i++){
if (used.contains(nums[i])){
continue;
}
if (sequence.isEmpty() || nums[i] >= sequence.peekLast()){
used.add(nums[i]);
sequence.add(nums[i]);
helper(sequence, i + 1, nums);
sequence.remove(sequence.size() - 1);
}
}
}
}
Time Complexity:
Space Complexity: