【Lintcode】1210. Increasing Subsequences

题目地址:

https://www.lintcode.com/problem/increasing-subsequences/description

给定一个整数数组,求其所有长度大于等于 2 2 2的(非严格)上升子序列。注意返回答案里不要包含完全相同的两个序列。

思路是DFS。主要难点在于去重。如果直接DFS,逐个枚举每个数字是否能加入path,当遇到形如 ( 2 , 3 , 2 , 4 ) (2,3,2,4) (2,3,2,4)这样的数组的时候, ( 2 , 4 ) (2,4) (2,4)会被枚举两次(枚举第一个 2 2 2的时候会枚举到这个path,枚举第二个 2 2 2的时候也会枚举到这个path)。这两个 2 2 2并不紧挨着,所以这里去重需要借助哈希表。枚举完一个数之后,就将其加入哈希表,下次遇到哈希表里存在的数字的时候就直接跳过。代码如下:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Solution {
    /**
     * @param nums: an integer array
     * @return: all the different possible increasing subsequences of the given array
     */
    public List<List<Integer>> findSubsequences(int[] nums) {
        // Write your code here
        List<List<Integer>> res = new ArrayList<>();
        dfs(0, nums, new ArrayList<>(), res);
        return res;
    }
    
    private void dfs(int pos, int[] nums, List<Integer> path, List<List<Integer>> res) {
    	// 将长度大于等于2的上升子序列加入答案
        if (path.size() >= 2) {
            res.add(new ArrayList<>(path));
        }
        
        // 枚举完了,返回
        if (pos == nums.length) {
            return;
        }
        
        Set<Integer> set = new HashSet<>();
        for (int i = pos; i < nums.length; i++) {
            if (set.contains(nums[i])) {
                continue;
            }
            
            set.add(nums[i]);
            
            if (path.isEmpty() || nums[i] >= path.get(path.size() - 1)) {
                path.add(nums[i]);
                dfs(i + 1, nums, path, res);
                // 回溯的时候恢复现场
                path.remove(path.size() - 1);
            }
        }
    }
}

时间复杂度 O ( n 2 n ) O(n2^n) O(n2n)(一共有最多 2 n 2^n 2n个答案,每个答案深拷贝一份需要 O ( n ) O(n) O(n)),空间 O ( n ) O(n) O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值