码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Subsets II

时间:2014-07-02 20:19:21      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   java   color   

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

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

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

 

思路:关键是去重,先排序,然后根据后一个是否跟前一个相等来判断是否继续递归。

bubuko.com,布布扣
import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {

        ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> tmp = new ArrayList<Integer>();
        // sort first
        Arrays.sort(num);
        sub(num, 0, tmp, ans);
        return ans;
    }

    public void sub(int[] num, int k, ArrayList<Integer> tmp, ArrayList<ArrayList<Integer>> ans) {
        ArrayList<Integer> arr = new ArrayList<Integer>(tmp);
        ans.add(arr);

        for (int i = k; i < num.length; i++) {
            // remove the dup
            if (i != k && num[i] == num[i - 1])
                continue;

            tmp.add(num[i]);
            sub(num, i + 1, tmp, ans);
            tmp.remove(tmp.size() - 1);
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution().subsetsWithDup(new int[] { 1, 2, 2 }));
    }
}
View Code

 

参考:

http://www.cnblogs.com/lautsie/p/3249869.html

[leetcode] Subsets II,布布扣,bubuko.com

[leetcode] Subsets II

标签:des   style   blog   http   java   color   

原文地址:http://www.cnblogs.com/jdflyfly/p/3819323.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!