491. Increasing Subsequences

来源:互联网 发布:mac充电 编辑:程序博客网 时间:2024/05/12 13:45

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]]

Note:

  1. The length of the given array will not exceed 15.
  2. The range of integer in the given array is [-100,100].
  3. The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.

原本的想法是从原数组减去一个数,但这样就不符合增序的要求。所以反过来,从单个数往上加,加的时候判断一下是否符合条件。

public class Solution {    public List<List<Integer>> findSubsequences(int[] nums) {        Set<List<Integer>> set=new HashSet<>();        LinkedList<Integer> hold=new LinkedList<>();        helper(hold,set,nums,0);        List res=new ArrayList(set);        return res;    }    public void helper(LinkedList<Integer> hold, Set<List<Integer>> set,int[] nums ,int index){        if(hold.size()>=2)            set.add(new LinkedList<>(hold));        for(int i=index;i<nums.length;i++){            if(hold.size()==0||hold.get(hold.size()-1)<=nums[i]){                hold.add(nums[i]);                helper(hold,set,nums,i+1);                hold.remove(hold.size()-1);            }        }    }}







0 0
原创粉丝点击