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

[leetcode]Subsets II

时间:2014-07-26 01:40:06      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   strong   io   

Subsets II

 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.

 

For example,
If S = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

算法思路:

[leetcode]Subsets 相比,只是多了一步去重复,其余木有区别,直接暴力。

代码如下:

 1 public class Solution { 
 2     List<List<Integer>> res = new ArrayList<List<Integer>>();
 3     public List<List<Integer>> subsetsWithDup(int[] num) {
 4         if(num == null || num.length == 0) return res;
 5         Arrays.sort(num);
 6         List<Integer> list = new ArrayList<Integer>();
 7         dfs(list,0,0,num);
 8         return res;
 9     }
10     private void dfs(List<Integer> list,int k ,int count,int[] num){
11         if(count <= num.length){
12             res.add(new ArrayList<Integer>(list));
13         }else{
14             return;
15         }
16         for(int i = k ; i < num.length; i++){
17             list.add(num[i]);
18             dfs(list,i + 1,count+1,num);
19             list.remove(list.size() - 1);
20             while(i < num.length - 1 && num[i] == num[i + 1]) i++;
21         }
22     }
23 }

 

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

[leetcode]Subsets II

标签:des   style   blog   http   color   os   strong   io   

原文地址:http://www.cnblogs.com/huntfor/p/3869141.html

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