首页 > 其他 > 详细

LeetCode Subsets II

时间:2015-09-27 11:13:08      阅读:250      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/subsets-ii/

Subsets的进阶版本。这里有duplicates, e.g. [1,2,2]但是res中不能包含两个[2].

所以在elem加完新元素想要放回res之前,需要先判断res中是否含有这个elem, 若是没有可以加到res中,若是已经有了,就不可以加到res中。

AC Java:

 1 public class Solution {
 2     public List<List<Integer>> subsetsWithDup(int[] nums) {
 3         List<List<Integer>> res = new ArrayList<List<Integer>>();
 4         if(nums == null || nums.length == 0){
 5             return res;
 6         }
 7         Arrays.sort(nums);
 8         res.add(new ArrayList<Integer>());
 9         for(int i = 0; i<nums.length; i++){
10             int size = res.size();
11             for(int j = 0; j<size; j++){
12                 ArrayList<Integer> elem = new ArrayList<Integer>(res.get(j));
13                 elem.add(nums[i]);
14                 if(!res.contains(elem)){
15                     res.add(elem);
16                 }
17             }
18         }
19         return res;
20     }
21 }

 

LeetCode Subsets II

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4841900.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!