zoukankan      html  css  js  c++  java
  • Leetcode 491.递增子序列

    递增子序列

    给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。

    示例:

    输入: [4, 6, 7, 7]

    输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]

    说明:

    1. 给定数组的长度不会超过15。
    2. 数组中的整数范围是 [-100,100]。
    3. 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。

    思路:

    利用递归的思想,维护一个栈,将每次找到的比当前栈顶大的数,然后入栈,将更新过后的栈扔进递归函数,然后更新查找的初始位置即从当前的位置后一个位置开始查找。递归函数结束后,取出栈顶,进入下个循环,这样将所有元素都作为栈底元素遍历一遍。

     1 import java.util.ArrayList;
     2 import java.util.HashSet;
     3 import java.util.List;
     4 import java.util.Set;
     5 
     6 public class Solution {
     7     public List<List<Integer>> findSubsequences(int[] nums) {
     8         Set<List<Integer>> res = new HashSet<List<Integer>>();
     9         helper(res, new ArrayList<Integer>(), nums, 0);
    10         return new ArrayList<List<Integer>>(res);
    11     }
    12 
    13     private void helper(Set<List<Integer>> res, List<Integer> subList, int[] nums, int start) {
    14         if (subList.size() >= 2) {
    15             res.add(new ArrayList<Integer>(subList));
    16         }
    17         for (int i = start; i < nums.length; i++) {
    18             if (subList.size() == 0 || subList.get(subList.size() - 1) <= nums[i]) {
    19                 subList.add(nums[i]);
    20                 helper(res, subList, nums, i + 1);
    21                 subList.remove(subList.size() - 1);
    22             }
    23         }
    24     }
    25 }
  • 相关阅读:
    python __builtins__ set类 (60)
    python __builtins__ reversed类 (58)
    python __builtins__ range类 (56)
    python __builtins__ property类 (55)
    python __builtins__ memoryview类 (46)
    python __builtins__ map类 (44)
    python __builtins__ list类 (42)
    python __builtins__ license类 (41)
    (转)面试算法总结
    (Mark)JS中的上下文
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10372504.html
Copyright © 2011-2022 走看看