mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0039.组合总和.md
This commit is contained in:
@ -236,7 +236,39 @@ public:
|
||||
|
||||
|
||||
Java:
|
||||
```Java
|
||||
class Solution {
|
||||
List<List<Integer>> lists = new ArrayList<>();
|
||||
Deque<Integer> deque = new LinkedList<>();
|
||||
|
||||
public List<List<Integer>> combinationSum3(int k, int n) {
|
||||
int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
|
||||
backTracking(arr, n, k, 0);
|
||||
return lists;
|
||||
}
|
||||
|
||||
public void backTracking(int[] arr, int n, int k, int startIndex) {
|
||||
//如果 n 小于0,没必要继续本次递归,已经不符合要求了
|
||||
if (n < 0) {
|
||||
return;
|
||||
}
|
||||
if (deque.size() == k) {
|
||||
if (n == 0) {
|
||||
lists.add(new ArrayList(deque));
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (int i = startIndex; i < arr.length - (k - deque.size()) + 1; i++) {
|
||||
deque.push(arr[i]);
|
||||
//减去当前元素
|
||||
n -= arr[i];
|
||||
backTracking(arr, n, k, i + 1);
|
||||
//恢复n
|
||||
n += deque.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python:
|
||||
|
||||
|
Reference in New Issue
Block a user