39. Combination Sum

Given a set of candidate numbers (C) (without duplicates) 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.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

[
  [7],
  [2, 2, 3]
]

一刷
题解:
DFS+backtracking

public class Solution {
    public List> combinationSum(int[] candidates, int target) {
        List> res = new ArrayList<>();
        if(candidates == null || candidates.length == 0) return res;
        permutation(res, candidates, target, 0, new ArrayList());
        return res;
    }
    
    public void permutation(List> res, int[] candidates, int target, int pos, List list){
        if(target == 0) {
            res.add(new ArrayList(list));
            return;
        }
        if(target<0) return;
        //if(pos>candidates.length-1) return;
        for(int i=pos; i

二刷:
DFS + Backtracking

public class Solution {
    public List> combinationSum(int[] candidates, int target) {
        List> res = new ArrayList<>();
        if(candidates == null || candidates.length == 0) return res;
        List list = new ArrayList<>();
        comb(res, list, 0, candidates, target);
        return res;
    }
    
    private void comb(List> res, List list, int index, int[] candidates, int target){
        if(target<0) return;
        if(target == 0){
            res.add(new ArrayList(list));
            return;
        }
        
        for(int i=index; i

你可能感兴趣的:(39. Combination Sum)