题目链接:LeetCode-39-组合总和
解题思路:
- 先排序,会节省时间;
- 由于数组中的数字可以无限制重复被选,,因此和前几道题的差别是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);}}
}