给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。
数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。
示例 1:
输入:nums = [4,6,7,7]
输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]示例 2:
输入:nums = [4,4,3,2,1] 输出:[[4,4]]
我们先来回顾一下 回溯 题的基本 模板:
void backtracking(参数) {
if (终止条件) {
存放结果;
return;
}for (选择:本层集合中元素) {
处理节点;
backtracking(路径,选择列表); // 递归
回溯,撤销处理结果
}
}
所以根据题目中明确说到,递增子序列中至少有两个元素,那么在终止条件就是当存放结果的长度 >= 2 时。 这次处理节点 需要有个前提条件,那么就是 递增子序列,如果上一个元素大于当前元素的话,则不添加。 能添加一定是递增的!!!并且题目 要求返回的是所有不同的子序列,那么我们可以利用 HashSet自带的性质: 去重
每次list添加元素时, set也添加,如果此次添加的元素set中包含的有的话,就continue。
代码:
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> list = new LinkedList<>();
// HashSet<List<Integer>> set = new HashSet<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtrack(nums, 0);
return res;
}
public void backtrack(int[] nums, int startIndex){
if(list.size() >= 2){
res.add(new ArrayList<>(list));
}
HashSet<Integer> set = new HashSet<>();
for(int i =startIndex; i<nums.length; i++){
if(set.contains(nums[i])) continue;
if(list.size() > 0 && nums[i] < list.get(list.size()-1)) continue;
list.add(nums[i]);
set.add(nums[i]);
backtrack(nums, i+1);
list.removeLast();
}
}
}
当然也可以先全部添加至HashSet里, set自带去重性质,全部遍历添加进去后,再遍历set,一个一个加入到我们保存结果的res中,但这样做的空间时间复杂度比较大
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> list = new LinkedList<>();
HashSet<List<Integer>> set = new HashSet<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtrack(nums, 0);
for(List<Integer> i : set){
res.add(i);
}
return res;
}
public void backtrack(int[] nums, int startIndex){
if(list.size() >= 2){
set.add(new ArrayList<>(list));
}
for(int i =startIndex; i<nums.length; i++){
if(list.size() > 0 && nums[i] < list.get(list.size()-1)) continue;
list.add(nums[i]);
backtrack(nums, i+1);
list.removeLast();
}
}
}