首页 > 其他 > 详细

Subsets II

时间:2015-03-10 22:57:34      阅读:296      评论:0      收藏:0      [点我收藏+]

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.

思路:

  dfs + 回溯

我的代码:

技术分享
public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] num) {
        if(num == null || num.length == 0)  return rst;
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(num);
        helper(list, num, 0);
        return rst;
    }
    private List<List<Integer>> rst = new ArrayList<List<Integer>>();
    public void helper(List<Integer> list, int[] candidates, int start)
    {
        rst.add(new ArrayList(list));
        for(int i = start ; i < candidates.length; i++)
        {
            if( i != start && candidates[i] == candidates[i-1]) continue;
            list.add(candidates[i]);
            helper(list, candidates, i + 1);
            list.remove(list.size() - 1);
        }
    }
}
View Code

学习之处:

  真正理解了程序,也就明白了if( i != start && candidates[i] == candidates[i-1]) continue;判断的精华所在了。

Subsets II

原文:http://www.cnblogs.com/sunshisonghit/p/4328430.html

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