LeetCode-491 递增子序列

题目描述:给一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。
示例:

输入: [4, 6, 7, 7]
输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]

说明:

  • 给定数组的长度不会超过15。
  • 数组中的整数范围是 [-100,100]。
  • 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。

思路:

这个题类似LeetCode-39(组合总和) 这道题,思路就是采用递归回溯的一般套路解决,不同的是这个题目最终需要采用set去重。

Java代码:

class Solution {
    
    
    public List<List<Integer>> findSubsequences(int[] nums) {
    
    
        Set<List<Integer>> res = new HashSet<>(); // 存放结果
        findSubList(res,nums,0,new ArrayList<Integer>());
        return new ArrayList<List<Integer>>(res); 
    }
    public void findSubList(Set<List<Integer>> res,int[] nums,int index,List<Integer> tempList){
    
    
        if(tempList.size()>=2){
    
        // 递增子序列的长度至少是2
            res.add(new ArrayList<>(tempList));
        }
        for(int i=index;i<nums.length;i++){
    
    
            if(tempList.size()==0 || tempList.get(tempList.size()-1) <= nums[i]){
    
    
                tempList.add(nums[i]);
                findSub(res,nums,i+1,tempList);   // 进行递归
                tempList.remove(tempList.size()-1);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/J0Han/article/details/96380089