递增子序列
考察知识点:DFS+Set(去重)
样例:
[4, 6, 7, 7]
ans:
[4,6] [4,7] [4,6,7] [4,7,7] [4,6,7,7]
[6,7] [6,7,7]
[7,7]
public static List<List<Integer>> findSubsequences(int[] nums){
Set<List<Integer>> paths = new HashSet<>(); //HashSet去重
List<Integer> path = new LinkedList<>();
dfs(nums,0,paths,path);
return new LinkedList<>(paths); //Set<List<Integer>>转List<List<Integer>>
}
public static void dfs(int[] nums,int pos,Set<List<Integer>> paths,List<Integer> path){
if(path.size()>=2){
paths.add(new LinkedList<>(path)); //path为引用地址,需new LinkedList实例化添加,不然结果集paths为空
}
for(int i=pos;i<nums.length;i++){
if(path.size()==0 || path.get(path.size()-1)<=nums[i]){
path.add(nums[i]);
dfs(nums,i+1,paths,path);
path.remove(path.size()-1);
}
}
}