491.递增子序列

78 阅读1分钟

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]。
  • 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。
class Solution {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> findSubsequences(int[] nums) {
        helper(nums,0);
        return result;
    }
    private void helper( int[] nums, int start ) {
        if(path.size()>1 ){
            result.add(new ArrayList<>(path));
            // 不加return,要取树上的节点
        }
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i=start; i < nums.length; i++){
            if(!path.isEmpty() && nums[i]< path.getLast()){
                continue;
            }
            // 使用过的元素跳过
            if (map.getOrDefault(nums[i],0) >= 1)continue;
            // 初次使用该元素->key从0化为1
            map.put(nums[i],map.getOrDefault(nums[i],0)+1);
            path.add( nums[i] );
            helper(nums,i+1);
            path.removeLast();
        }
    }
}