Problem 90

Subsets II

Posted by Ruizhi Ma on August 13, 2019

问题描述

https://leetcode.com/problems/subsets-ii/

解决思路

同78题,需要加入判断重复。

代码

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        //corner case
        if(nums.length == 0 || nums == null) return res;
        
        helper(nums, res, new ArrayList<>(), 0);
        
        return res;
    }
    
    public void helper(int[] nums, List<List<Integer>> res, List<Integer> list, int start){
        res.add(new ArrayList<>(list));
        for(int i = start; i < nums.length; i++){
            if(i > start && nums[i] == nums[i - 1]) continue;
            list.add(nums[i]);
            helper(nums, res, list, i + 1);
            list.remove(list.size() - 1);
        }
    }
}

复杂度分析

  1. 时间复杂度:O(2^n)
  2. 空间复杂度:O(1)

0 comments
Anonymous
Error: Bad credentials.
Markdown is supported

Be the first person to leave a comment!