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

Subsets II

时间:2015-03-10 22:59:27      阅读:169      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!