Combination Sum

来源:互联网 发布:简单冒泡排序算法 编辑:程序博客网 时间:2024/06/05 15:48
public class Solution {    public List<List<Integer>> combinationSum(int[] candidates, int target) {        List<List<Integer>> res = new LinkedList<>();        if (candidates == null || candidates.length == 0) {            return res;        }        List<Integer> list = new LinkedList<>();        Arrays.sort(candidates);        helper(res, list, candidates, target, 0, 0);            return res;    }        private void helper(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int sum, int pos) {        if (sum == target) {            res.add(new LinkedList<>(list));            return;        }        for (int i = pos; i < candidates.length; i++) {            if (sum + candidates[i] > target) {                return;            }            list.add(candidates[i]);            helper(res, list, candidates, target, sum + candidates[i], i);            list.remove(list.size() - 1);        }    }}

0 0