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

[LeetCode]40 Combination Sum II

时间:2015-01-03 08:12:50      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:leetcode   np   

https://oj.leetcode.com/problems/combination-sum-ii/

http://blog.csdn.net/linhuanmars/article/details/20829099

public class Solution {
    public List<List<Integer>> combinationSum2(int[] num, int target)
    {
        if (num == null || num.length == 0)
            return Collections.emptyList();

        // Sort
        Arrays.sort(num);

        Set<List<Integer>> result = new HashSet<>();        
        sum(num, target, 0, new ArrayList<Integer>(), result);
        return new ArrayList<List<Integer>>(result);
    }
    
    private void sum(int[] num, int t, int start, List<Integer> curnums, Set<List<Integer>> result)
    {
        if (t < 0)
            return;
            
        if (t == 0)
        {
            List<Integer> r = new ArrayList<>(curnums);
            Collections.sort(r);
            result.add(r);
            return;
        }
        
        for (int i = start ; i < num.length ; i ++)
        {
            curnums.add(num[i]);
            
            // 由于每个数字只能被用到以此,所以 nextstart = i + 1
            // 这是和 combination sum 问题的区别
            // 而且,这导致了结果集有可能有重复
            // 比如 输入数组有两个2
            // 一个结果了使用 第一个2
            // 另一个结果使用了 第二个2
            // 需要使用set去除重复
            int nextstart = i + 1;
            sum(num, t - num[i], i + 1, curnums, result);
            
            curnums.remove(curnums.size() - 1);
        }
    }
}


[LeetCode]40 Combination Sum II

标签:leetcode   np   

原文地址:http://7371901.blog.51cto.com/7361901/1598590

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