作者:手机用户2502928341 | 来源:互联网 | 2023-10-11 16:57
代码1(自己)
class Solution {
List> res = new ArrayList<>();
List path = new ArrayList<>();
public List> combinationSum3(int k, int n) {
backtracking(k, n, 1);
return res;
}
public void backtracking(int k, int n, int startIndex) {
if (path.size() == k) {
if (getSum(path) == n) {
res.add(new ArrayList<>(path));
//return;
}
return;
}
for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i ++) {
path.add(i);
backtracking(k, n, i + 1);
path.remove(path.size() - 1);
}
}
public int getSum(List path) {
int sum = 0;
for (int i = 0; i sum += path.get(i);
}
return sum;
}
}
剪枝操作: for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i ++) {}
代码2(代码随想录)
class Solution {
List> res = new ArrayList<>();
List path = new ArrayList<>();
public List> combinationSum3(int k, int n) {
backtracking(k, n, 0, 1);
return res;
}
public void backtracking(int k, int n, int sum, int startIndex) {
if (path.size() == k) {
if (sum == n) {
res.add(new ArrayList<>(path));
}
return;
}
for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i ++) {
sum += i; // 处理
path.add(i); // 处理
backtracking(k, n, sum, i + 1); // 回溯
sum -= i; // 撤销
path.remove(path.size() - 1); // 撤销
}
}
}
注意:
恢复现场
处理过程和回溯过程是一一对应的,处理过程中有加法操作,回溯过程就要有对应的减法操作。