Middle-题目57:90. Subsets II

原创 2016年05月31日 16:28:20

题目原文:
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
题目大意:
Middle-题目52,但这里面的数组会有重复元素,但子集中仍不允许有重复元素。
题目分析:
这次适合回溯法,但要注意,如果遇到当前数字和前一个数字相同,则跳过去。
使用backtrack(int[] nums, int index, List<List<Integer>> result, List<Integer> sublist)函数记录搜索过程,其中index记录当前搜索到的数字的索引(相同时索引取最后一个),那么如果循环时nums[i]==nums[i-1]时则跳过。
源码:(language:java)

public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> result = new ArrayList<> ();
        if(nums == null) {
            return result;
        }
        Arrays.sort(nums);
        backtrack(nums, 0, result, new ArrayList<Integer> ());
        return result;
    }

    private void backtrack(int[] nums, int index, List<List<Integer>> result, List<Integer> sublist) {
        if(index <= nums.length) {
            result.add(new ArrayList<> (sublist));
        }
        for(int i = index; i < nums.length; i++) {
            if(i != index && nums[i] == nums[i - 1]) {
                continue;
            }
            sublist.add(nums[i]);
            backtrack(nums, i + 1, result, sublist);
            sublist.remove(sublist.size() - 1);
        }
    }
}

成绩:
3ms,beats 41.85%,众数3ms,41.53%
Cmershen的碎碎念:
一个较笨的办法就是在上一题的基础上判断是否存在这个集合序列,但时间长达37ms,因为这样会搜出很多无效解。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

leetcode 90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...

【leetcode】90. Subsets II

leetcode, subsets ||, 3种解法

[leetcode 78 & 90, Medium] Subsets I and II

Subsets I and II

leetcode 90 Subsets II

leetcode 90 Subsets II c++ Python

LeetCode 90 Subsets II--In C++

思路: 由于这道题增加了冗余的属性,所以如果用Subset 1中的暴力递归进行求解的话,会浪费很多时间在扫描判断是否有重复值上。因此,类似于全排列的那个题,想到了在之前的基础上添加一个元素即可形成全...

LeetCode 90 Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets. No...

LeetCode 78, 90. Subsets i, ii

1. 题目描述 Given a set of distinct integers, nums, return all possible subsets. Note: Element...

【LeetCode】90. Subsets II解法及注释

90. Subsets II Total Accepted: 65104 Total Submissions: 214320 Difficulty: Medium Given a collecti...

90. Subsets II -Medium

Question Given a collection of integers that might contain duplicates, nums, return all possible s...

[LeetCode]90.Subsets II

题目Given a collection of integers that might contain duplicates, S, return all possible subsets.Note:...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)