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]]
Solution: 每层用hashset去重
public List<List<Integer>> findSubsequences(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
if (nums == null || nums.length == 0) {
return ans;
}
helper(ans, new ArrayList<Integer>(), 0, nums);
return ans;
}
private void helper(List<List<Integer>> ans, List<Integer> path, int index, int[] nums) {
if (path.size() > 1) {
ans.add(new ArrayList<>(path));
}
Set<Integer> hashset = new HashSet<>();
for (int i = index; i < nums.length; i++) {
if (!hashset.contains(nums[i]) && (path.size() == 0 || nums[i] >= path.get(path.size() - 1))) {
hashset.add(nums[i]);
path.add(nums[i]);
//注意是i + 1,不是index + 1
helper(ans, path, i + 1, nums);
path.remove(path.size() - 1);
}
}
}