Leecode491:递增子序列
-
题目:
-
给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。
数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。
-
-
思路:回溯算法+代码注释
-
代码如下:
class Solution {
//二维数组存放结果集
List<List<Integer>> res = new ArrayList<>();
//一维数组存放临时路径
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
//回溯算法
backtrack( nums, 0 );
return res;
}
void backtrack( int[] nums, int startIndex ) {
//当路径节点大于等于2时,直接添加节点到结果集
if ( path.size() > 1 ) {
res.add( new ArrayList<>(path) );
}
//定义HashMap数组,用于判断是否在同一树层使用相同的元素
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i = startIndex; i < nums.length; i++){
if (!path.isEmpty() && nums[i] < path.getLast() ) {
//判断当前路径为空或当前数小于路径的最后一个数
continue;
}
//说明当前路径不为空且当前数大于路径的最后一个数
if ( map.getOrDefault( nums[i], 0 ) >= 1 ) {
//说明在同一树层中使用了相同的元素
continue;
}
//说明在同一树层中使用了不同的元素
map.put( nums[i], map.getOrDefault( nums[i], 0 ) + 1 );
path.add( nums[i] );
backtrack( nums, i + 1 );
path.remove( path.size() - 1 );
}
}
}