mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
添加39. 组合总和JavaScript版本
This commit is contained in:
@ -286,28 +286,28 @@ class Solution:
|
|||||||
```
|
```
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
JavaScript
|
JavaScript:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
var strStr = function (haystack, needle) {
|
var combinationSum = function(candidates, target) {
|
||||||
if (needle === '') {
|
const res = [], path = [];
|
||||||
return 0;
|
candidates.sort(); // 排序
|
||||||
|
backtracking(0, 0);
|
||||||
|
return res;
|
||||||
|
function backtracking(j, sum) {
|
||||||
|
if (sum > target) return;
|
||||||
|
if (sum === target) {
|
||||||
|
res.push(Array.from(path));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
for(let i = j; i < candidates.length; i++ ) {
|
||||||
let hayslen = haystack.length;
|
const n = candidates[i];
|
||||||
let needlen = needle.length;
|
if(n > target - sum) continue;
|
||||||
|
path.push(n);
|
||||||
if (haystack === '' || hayslen < needlen) {
|
sum += n;
|
||||||
return -1;
|
backtracking(i, sum);
|
||||||
}
|
path.pop();
|
||||||
|
sum -= n;
|
||||||
for (let i = 0; i <= hayslen - needlen; i++) {
|
|
||||||
if (haystack[i] === needle[0]) {
|
|
||||||
if (haystack.substr(i, needlen) === needle) {
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (i === hayslen - needlen) {
|
|
||||||
return -1;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
Reference in New Issue
Block a user