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<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(candidates == null || candidates.length == 0) return res;
        permutation(res, candidates, target, 0, new ArrayList<Integer>());
        return res;
    }
    
    public void permutation(List<List<Integer>> res, int[] candidates, int target, int pos, List<Integer> list){
        if(target == 0) {
            res.add(new ArrayList<Integer>(list));
            return;
        }
        if(target<0) return;
        //if(pos>candidates.length-1) return;
        for(int i=pos; i<candidates.length; i++){
            list.add(candidates[i]);
            permutation(res, candidates, target - candidates[i], i, list);
            list.remove(list.size()-1);
        }
        return;
    }
}

二刷:
DFS + Backtracking

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(candidates == null || candidates.length == 0) return res;
        List<Integer> list = new ArrayList<>();
        comb(res, list, 0, candidates, target);
        return res;
    }
    
    private void comb(List<List<Integer>> res, List<Integer> list, int index, int[] candidates, int target){
        if(target<0) return;
        if(target == 0){
            res.add(new ArrayList<Integer>(list));
            return;
        }
        
        for(int i=index; i<candidates.length; i++){
            list.add(candidates[i]);
            comb(res, list, i, candidates, target - candidates[i]);
            list.remove(list.size()-1);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容