zoukankan      html  css  js  c++  java
  • [LeetCode] 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]]

    Constraints:

    • 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.

    递增子序列。题意是给一个无序的整型int数组,请你返回所有递增的子序列。相等的元素也视为递增。

    思路是回溯backtracking。还是会利用到经典的回溯模板,这道题只需要在几个地方略加修改即可。首先因为input里面会有重复的数字,如果是连在一起的相同数字,也会被视为递增,所以一定要用一个hashset帮助去重。去重的方式有两种,一是在回溯的过程中进行去重,另一种是对结果集进行去重。我这里是对结果集进行去重。

    其次回溯的base case是只要子集长度大于1就可以加入结果集。回溯的过程中,只要后一个数字 >= 前一个数字,就加入当前子集并进入下一层的递归。

    时间O(2^n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public List<List<Integer>> findSubsequences(int[] nums) {
     3         HashSet<List<Integer>> set = new HashSet<>();
     4         if (nums == null || nums.length == 0) {
     5             return new ArrayList<>();
     6         }
     7         helper(set, new ArrayList<>(), nums, 0);
     8         List res = new ArrayList<>(set);
     9         return res;
    10     }
    11 
    12     private void helper(HashSet<List<Integer>> set, List<Integer> list, int[] nums, int start) {
    13         if (list.size() > 1) {
    14             set.add(new ArrayList<>(list));
    15         }
    16         for (int i = start; i < nums.length; i++) {
    17             if (list.size() == 0 || list.get(list.size() - 1) <= nums[i]) {
    18                 list.add(nums[i]);
    19                 helper(set, list, nums, i + 1);
    20                 list.remove(list.size() - 1);
    21             }
    22         }
    23     }
    24 }

    LeetCode 题目总结

  • 相关阅读:
    hbase删除标记和注意事项
    马上拥有一台自己的云服务器
    在 Ubuntu 开启 GO 程序编译之旅
    在 Ubuntu 上安装 Protobuf 3
    功能设计中技术人员之惑
    关于数据可视化页面制作
    快速响应请求浅谈
    自定义一个代码耗时计数工具类
    一种极简的异步超时处理机制设计与实现(C#版)
    百度地图API图标、文本、图例与连线
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13737526.html
Copyright © 2011-2022 走看看