mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
添加·216.组合总和IIIJavaScript版本
This commit is contained in:
@ -180,7 +180,7 @@ if (sum > targetSum) { // 剪枝操作
|
|||||||
|
|
||||||
最后C++代码如下:
|
最后C++代码如下:
|
||||||
|
|
||||||
```
|
```c++
|
||||||
class Solution {
|
class Solution {
|
||||||
private:
|
private:
|
||||||
vector<vector<int>> result; // 存放结果集
|
vector<vector<int>> result; // 存放结果集
|
||||||
@ -262,7 +262,7 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
```python3
|
```py
|
||||||
class Solution:
|
class Solution:
|
||||||
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
|
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
|
||||||
res = [] #存放结果集
|
res = [] #存放结果集
|
||||||
@ -284,6 +284,44 @@ class Solution:
|
|||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
javaScript:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// 等差数列
|
||||||
|
var maxV = k => k * (9 + 10 - k) / 2;
|
||||||
|
var minV = k => k * (1 + k) / 2;
|
||||||
|
var combinationSum3 = function(k, n) {
|
||||||
|
if (k > 9 || k < 1) return [];
|
||||||
|
// if (n > maxV(k) || n < minV(k)) return [];
|
||||||
|
// if (n === maxV(k)) return [Array.from({length: k}).map((v, i) => 9 - i)];
|
||||||
|
// if (n === minV(k)) return [Array.from({length: k}).map((v, i) => i + 1)];
|
||||||
|
|
||||||
|
const res = [], path = [];
|
||||||
|
backtracking(k, n, 1, 0);
|
||||||
|
return res;
|
||||||
|
function backtracking(k, n, i, sum){
|
||||||
|
const len = path.length;
|
||||||
|
if (len > k || sum > n) return;
|
||||||
|
if (maxV(k - len) < n - sum) return;
|
||||||
|
if (minV(k - len) > n - sum) return;
|
||||||
|
|
||||||
|
if(len === k && sum == n) {
|
||||||
|
res.push(Array.from(path));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const min = Math.min(n - sum, 9 + len - k + 1);
|
||||||
|
|
||||||
|
for(let a = i; a <= min; a++) {
|
||||||
|
path.push(a);
|
||||||
|
sum += a;
|
||||||
|
backtracking(k, n, a + 1, sum);
|
||||||
|
path.pop();
|
||||||
|
sum -= a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user