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

    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.

    Approach #1: DFS. [Java]

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

      

    Analysis:

    Using the list.size() as the foundation to process dfs.

    Reference:

    https://leetcode.com/problems/increasing-subsequences/discuss/97147/Java-solution-beats-100

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    WC命令
    dcoker machine
    linux命令
    Valgrind 检测程序内存使用
    golang flag
    面试之---二叉树的遍历
    FFMpeg 版本错误
    C++中namespace的使用
    QT之QStatusBar
    建立ftp服务器和客户端
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10957852.html
Copyright © 2011-2022 走看看