491 Increasing Subsequences

class Solution {
    public List<List<Integer>> findSubsequences(int[] nums) {
        // List<List<Integer>> result = new ArrayList<>();
        // use set to deduplicate 
        Set<List<Integer>> result = new HashSet<>();
        List<Integer> tmp = new ArrayList<>();
        dfs(result, tmp, nums, 0);
        //return result;
        // convert hashset to list 
        return new ArrayList<>(result);
    }
    private void dfs(Set<List<Integer>> result, List<Integer> tmp, int[] nums, int index){
        if(tmp.size() >= 2){
            result.add(new ArrayList<>(tmp));
            // no return here because we need to keep adding until hit the boundary 
        }
        
        
        for(int i = index; i < nums.length; i++){
            if(tmp.size() == 0 || tmp.get(tmp.size() -1) <= nums[i]){ // <=
                tmp.add(nums[i]);
                dfs(result, tmp, nums, i + 1);
                tmp.remove(tmp.size() - 1);
            }
        }
    }
}

 

Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be 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]]

 

 idea, start at one index, for the first pos, we can choose all index, so we can  have number 4, 6, 7, 7 as the first number of out increasing subsequence

for the second number, we must choose the number whose index is bigger then the index at the prev pos, and the value must be bigger than the 

value at the prev pos, for the third number in this non decreasing subsequence, we choose the number whose index is bigger than the index of prev 

pos, and the value is also bigger than the previous value, 

 

since the size of the subseunce is bigger or equal to 2 , so when we reach the subsequence of  size 2 , we add it to the result and 

we continue with this subsequence and add more numbers if possible, because we want to return all non decreeasing of subsequnce with size >= 2 

 

 

the stopping condition is when the starting index hits the nums boundary, 

this is how this problem different from other backtracking problems base case, this one doesn't have return, because it keeps going until hit the boundary 

 

posted on 2018-08-10 14:46  猪猪&#128055;  阅读(132)  评论(0)    收藏  举报

导航