[Lintcode] Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.


For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

 Notice
  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.
Example

given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

递归算法,难点是查重。此处使用ArrayList自带函数contains查重。 首先进行排序,排序后每次从当前元素开始递归,从而保证同一个元素在结果集合中出现多次的情况。终止条件是index超过candidates或者target小于0 或者等于0


public class Solution {
    /**
     * @param candidates: A list of integers
     * @param target:An integer
     * @return: A list of lists of integers
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        helper(res, new ArrayList<Integer>(), candidates, target, 0);
        return res;
    }
    void helper(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int index) {
        if(target == 0 && !res.contains(list)) {
            res.add(new ArrayList(list));
            return;
        }
        if(index >= candidates.length || target < 0)
            return;
            
        for(int i = index; i < candidates.length; i++) {
            list.add(candidates[i]);
            helper(res, list, candidates, target - candidates[i], i);
            list.remove(list.size() - 1);
        }
    }
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jc69186918/article/details/52345769
文章标签: lintcode
个人分类: 算法
上一篇**[Lintcode]Coins in a Line II
下一篇[Lintcode] Combination Sum II
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭