mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
0216.组合总和III
增加一种更简单的剪裁方式。
This commit is contained in:
@ -260,6 +260,37 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 上面剪枝 i <= 9 - (k - path.size()) + 1; 如果还是不清楚
|
||||||
|
// 也可以改为 if (path.size() > k) return; 执行效率上是一样的
|
||||||
|
class Solution {
|
||||||
|
LinkedList<Integer> path = new LinkedList<>();
|
||||||
|
List<List<Integer>> ans = new ArrayList<>();
|
||||||
|
public List<List<Integer>> combinationSum3(int k, int n) {
|
||||||
|
build(k, n, 1, 0);
|
||||||
|
return ans;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void build(int k, int n, int startIndex, int sum) {
|
||||||
|
|
||||||
|
if (sum > n) return;
|
||||||
|
|
||||||
|
if (path.size() > k) return;
|
||||||
|
|
||||||
|
if (sum == n && path.size() == k) {
|
||||||
|
ans.add(new ArrayList<>(path));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for(int i = startIndex; i <= 9; i++) {
|
||||||
|
path.add(i);
|
||||||
|
sum += i;
|
||||||
|
build(k, n, i + 1, sum);
|
||||||
|
sum -= i;
|
||||||
|
path.removeLast();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
其他方法
|
其他方法
|
||||||
|
Reference in New Issue
Block a user