题目描述:
标签:深度优先搜索
给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是 2 。
代码:
思路分析:注意和求 子集 和 去重 的区别!
1、首先不能对数组进行排序,因为排序后都是递增的序列了!
2、递归结束条件一样是,startIndex > nums.length,可以不写,因为循环里也同样判断了
3、从左到右遍历相同,是startIndex开始
4、从上到下遍历,要记得去重,去重原则是建立一个hash数组,因为-100<=nums[i]<=100,所以长度为201,记录同一层中是否使用过该数,不需要在回溯返回是设置used=0,因为这样就相当于不记得同层使用过这个数了,没达到去重效果
5、回溯结束,只需移除末尾元素
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backTracing(nums,0);
return result;
}
public void backTracing(int[] nums,int stratIndex){
if(path.size() > 1){
result.add(new ArrayList<Integer>(path));
}
int[] used = new int[201];
for(int i = stratIndex;i < nums.length;i++){
if((!path.isEmpty() && nums[i] < path.get(path.size()-1)) || used[nums[i] + 100 ] == 1){
continue;
}
path.add(nums[i]);
used[nums[i] + 100] = 1;
backTracing(nums,i+1);
path.remove(path.size()-1);
}
}
}