Leetcode-90. Subsets II

来源:互联网 发布:app下载排名 优化 编辑:程序博客网 时间:2024/06/05 06:18

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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

Note: 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],  []]
这个题目还是用了递归做,还行吧。Your runtime beats 29.37% of java submissions.

public class Solution {    public List<List<Integer>> subsetsWithDup(int[] nums) {        List<List<Integer>> results = new ArrayList<List<Integer>>();        List<Integer> currentResults = new ArrayList<Integer>();        List<Integer> remains = new ArrayList<Integer>();        Arrays.sort(nums);        for(int item : nums) remains.add(item);        if(nums.length == 0) return results;        generate(results,currentResults,remains);        results.add(new ArrayList<Integer>());        return results;    }    public void generate(List<List<Integer>> results, List<Integer>currentResults, List<Integer> remains){        int times = remains.size();        for(int i = 0 ; i < times;){            int val = remains.get(0);            currentResults.add(remains.get(0));            List<Integer> result = new ArrayList<Integer>(currentResults);            results.add(result);            remains.remove(0);            generate(results,currentResults,new ArrayList<Integer>(remains));            currentResults.remove(currentResults.size()-1);            i++;            while(i < times) {if(remains.get(0) == val){ i++;remains.remove(0);}else break;}        }    }}






0 0
原创粉丝点击