2021.11.25 - SX08-07.组合总和
作者:互联网
文章目录
1. 题目
2. 思路
(1) 回溯法
- 首先将数组进行排序,然后可以将剪枝策略放到for循环中,当路径之和已经大于目标值时,直接返回即可,这样可以节省大量入栈出栈的时间。
3. 代码
import java.util.*;
public class Test {
public static void main(String[] args) {
}
}
class Solution {
private List<List<Integer>> res;
private LinkedList<Integer> stack;
private int[] candidates;
private int target;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
res = new ArrayList<>();
stack = new LinkedList<>();
this.candidates = candidates;
this.target = target;
Arrays.sort(candidates);
backtrack(0, 0);
return res;
}
private void backtrack(int index, int sum) {
if (sum == target) {
res.add(new ArrayList<>(stack));
return;
}
for (int i = index; i < candidates.length; i++) {
int next = sum + candidates[i];
if (next > target) {
return;
}
stack.addLast(candidates[i]);
backtrack(i, next);
stack.removeLast();
}
}
}
标签:25,2021.11,target,int,res,private,candidates,stack,SX08 来源: https://blog.csdn.net/qq_44021223/article/details/121544256