JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order.

The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.

Example 1:

Input: nums = [4,6,7,7]
Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]

Example 2:

Input: nums = [4,4,3,2,1]
Output: [[4,4]]

Constraints:

  • 1 <= nums.length <= 15
  • -100 <= nums[i] <= 100

Code

class Solution {
    public List<List<Integer>> findSubsequences(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();

        dfs(res, 0, nums, new ArrayList<>());
        return res;
    }

    private void dfs(List<List<Integer>> res, int start, int[] nums, ArrayList<Integer> temp){
        if(temp.size() >= 2) {
            res.add(new ArrayList<>(temp));
        }

        HashSet<Integer> visited = new HashSet<>();

        for(int i = start; i < nums.length; i++){
            int curr = nums[i];

            if(visited.contains(curr)) continue;

            if(temp.size() == 0 || curr >= temp.get(temp.size() - 1)){
                visited.add(curr);
                temp.add(curr);
                dfs(res, i + 1, nums, temp);
                temp.remove(temp.size() - 1);
            }
        }
    }
}