【Leetcode】491. Increasing Subsequences

Question

491. Increasing Subsequences
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:
The length of the given array will not exceed 15.
The range of integer in the given array is [-100,100].
The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.

Analysis

递归回溯(DFS)找到所有的递增子序列,使用set来自动去除重复的项。

Solution

class Solution {
    public List<List<Integer>> findSubsequences(int[] nums) {
        Set<List<Integer>> res = new HashSet<>();
        List<Integer> holder = new ArrayList<>();
        findSubsequence(res,holder,0,nums);
        List ans = new ArrayList(res);
        return ans;
    }
    private void findSubsequence(Set<List<Integer>> res,List<Integer>  holder,int index, int[] nums){
        if(holder.size() >= 2){
            res.add(new ArrayList(holder));
        }
        for(int i = index;i<nums.length;i++){
            if(holder.size()==0 || holder.get(holder.size()-1) <= nums[i]){
                holder.add(nums[i]);
                findSubsequence(res,holder,i+1,nums);
                holder.remove(holder.size()-1);
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,789评论 0 33
  • wordpress优化,主要是放在当前主题下的functions.php下
    malingxin阅读 887评论 0 3
  • 刘溪,远大住工国际;国学践行23期学员,24期奉献者,六项精进299期同修【知~学习》 【日精进第10天】 《六项...
    西西_3e45阅读 136评论 0 0
  • 就在那一刻,安吉列娜将自己的心一寸寸冷冻起来,她再也不想让阳光射入那个角落,明明互相说的都是祝福对方的话语,可安吉...
    Sunsy阅读 324评论 0 0
  • 每个人都喜欢按时间来做一个结束,做一个开始。尤其是每一年的1月1日,是一个大开始,大家都在那是立下新年愿望,新年目...
    茶茶苏阅读 233评论 0 0