LeetCode-39-组合总和

题目链接:LeetCode-39-组合总和

解题思路:

  1. 先排序,会节省时间;
  2. 由于数组中的数字可以无限制重复被选,,因此和前几道题的差别是index不需要+1,而是可以继续选择当前的元素

代码实现:

class Solution {
    List<List<Integer>> res = new ArrayList<>();// 创建两个全局变量
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backTracking(candidates, target, 0,0);
        return res;
    }

    public void backTracking(int[] candidates, int target, int index, int curSum){
        if (target == curSum){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (curSum+candidates[i] > target){// 这种情况也要考虑到
                continue;
            }
            path.add(candidates[i]);
            backTracking(candidates,target,i,curSum+candidates[i]);
            path.remove(path.size()-1);
        }
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法)