添加39. 组合总和JavaScript版本

This commit is contained in:
qingyi.liu
2021-06-05 18:42:38 +08:00
parent 7cbf0b1fff
commit d6955ebf03

View File

@ -286,30 +286,30 @@ 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;
let hayslen = haystack.length; function backtracking(j, sum) {
let needlen = needle.length; if (sum > target) return;
if (sum === target) {
if (haystack === '' || hayslen < needlen) { res.push(Array.from(path));
return -1; return;
} }
for(let i = j; i < candidates.length; i++ ) {
for (let i = 0; i <= hayslen - needlen; i++) { const n = candidates[i];
if (haystack[i] === needle[0]) { if(n > target - sum) continue;
if (haystack.substr(i, needlen) === needle) { path.push(n);
return i; sum += n;
} backtracking(i, sum);
path.pop();
sum -= n;
}
} }
if (i === hayslen - needlen) {
return -1;
}
}
}; };
``` ```