Leetcode of backtracking depth-first search & thematic -491. Increasing subsequence (Increasing Subsequences)

Leetcode of backtracking depth-first search & thematic -491. Increasing subsequence (Increasing Subsequences)

Problem-solving depth-first search details, click


 

Given an array of integers, your task is to find all increasing subsequence of the array, increasing subsequence length is at least 2. 

Example: 

Input: [ 4, 6, 7, 7 ] 
Output: [[ 4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7 ], [6, 7, 7], [7,7], [4,7,7 ]] 
Description: the 

length of the array is given less than 15. 
The array is an integer ranging from [ -100,100 ]. 
Given array may contain duplicate numbers, equal numbers should be seen as a case of increasing.

 

Entered from the first element, taking list number greater than or equal to the last element, and then back.

 

AC Code:

class Solution {
    Set<List<Integer>> ans = new HashSet<>();
    public List<List<Integer>> findSubsequences(int[] nums) {
        if(nums.length==0 || nums==null) return new ArrayList<>(ans);
        dfs(nums,0,new ArrayList<Integer>());
        return new ArrayList<>(ans);
    }
    
    private void dfs(int[] nums, int step, ArrayList<Integer> list) {
        if(list.size()>=2){
            ans.add(new ArrayList<>(list));
        }
        
        for(int i=step;i<nums.length;i++){
            if(!list.isEmpty() && list.get(list.size()-1)>nums[i]){
                continue;
            }
            list.add(nums[i]);
            dfs(nums,i+1,list);
            list.remove(list.size()-1);
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11367013.html