lintcode-medium-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 (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

 

回溯算法(backtracking),因为每个数可以使用任意次,所以每次递归的时候都从当前的起点开始

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) {
        // write your code here
        
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        
        if(candidates == null || candidates.length == 0)
            return result;
        
        List<Integer> line = new ArrayList<Integer>();
        Arrays.sort(candidates);
        
        helper(result, line, candidates, target, 0);
        
        return result;
    }
    
    public void helper(List<List<Integer>> result, List<Integer> line, int[] candidates, int target, int start){
        
        if(target < 0)
            return;
        
        if(target == 0){
            result.add(new ArrayList<Integer>(line));
            return;
        }
        
        
        for(int i = start; i < candidates.length; i++){
            line.add(candidates[i]);
            helper(result, line, candidates, target - candidates[i], i);
            line.remove(line.size() - 1);
        }
        
        return;
    }
    
}

 

 

posted @ 2016-03-16 06:29  哥布林工程师  阅读(146)  评论(0编辑  收藏  举报