Skip to content

Commit

Permalink
Update 0039.组合总和.md
Browse files Browse the repository at this point in the history
  • Loading branch information
nanhuaibeian authored May 12, 2021
1 parent f950596 commit 988211e
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions problems/0039.组合总和.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down

0 comments on commit 988211e

Please sign in to comment.