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.

    用backtracking,set去重

    time: O(2^n), space: O(n)

    class Solution {
        public List<List<Integer>> findSubsequences(int[] nums) {
            Set<List<Integer>> res = new HashSet<>();
            if(nums == null || nums.length == 0) return new ArrayList<>(res);
            dfs(nums, 0, new ArrayList<>(), res);
            return new ArrayList<>(res);
        }
        private void dfs(int[] nums, int idx, List<Integer> tmp, Set<List<Integer>> res) {
            if(tmp.size() >= 2 && !res.contains(tmp))
                res.add(new ArrayList<>(tmp));
    
            for(int i = idx; i < nums.length; i++) {
                if(tmp.size() == 0 || nums[i] >= tmp.get(tmp.size() - 1)) {
                    tmp.add(nums[i]);
                    dfs(nums, i + 1, tmp, res);
                    tmp.remove(tmp.size() - 1);
                }
            }
        }
    }
  • 相关阅读:
    洛谷 P1767 家族_NOI导刊2010普及(10)
    洛谷 P2919 [USACO08NOV]守护农场Guarding the Farm
    COGS 1619. [HEOI2012]采花
    UVA 11181 Probability|Given
    hdu 3336 Count the string
    洛谷 P2176 [USACO14FEB]路障Roadblock
    洛谷 P2691 逃离
    BZOJ 1040: [ZJOI2008]骑士
    vijos 1320 清点人数
    POJ 3417 Network
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10078532.html
Copyright © 2011-2022 走看看