添加39. 组合总和JavaScript版本

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

View File

@ -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;
} }
} }
}; };