难度:medium
一般的回溯题大同小异,多了一个判断递增的过程;
但这道题是求递增子序列,所以不能用前面的排序后用标记数组来去重的方法;
可以使用HashSet或者数组来去重;
Java:
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtracking(nums, 0);
return ans;
}
public void backtracking(int[] nums, int startIndex) {
if (path.size() > 1) {
ans.add(new ArrayList<>(path));
}
if (startIndex >= nums.length) {
return;
}
HashSet<Integer> set = new HashSet<>();
for (int i = startIndex; i < nums.length; i++) {
// 是否是重复元素
if (set.contains(nums[i])) {
continue;
}
// 判断是否递增
if (!path.isEmpty() && nums[i] < path.get(path.size() - 1)) {
continue;
}
set.add(nums[i]);
path.add(nums[i]);
backtracking(nums, i + 1);
path.remove(path.size() - 1);
}
}
}