diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index e1023ec9..e3e4a117 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -286,30 +286,30 @@ class Solution: ``` Go: -JavaScript +JavaScript: + ```js -var strStr = function (haystack, needle) { - if (needle === '') { - return 0; - } - - let hayslen = haystack.length; - let needlen = needle.length; - - if (haystack === '' || hayslen < needlen) { - return -1; - } - - for (let i = 0; i <= hayslen - needlen; i++) { - if (haystack[i] === needle[0]) { - if (haystack.substr(i, needlen) === needle) { - return i; - } +var combinationSum = function(candidates, target) { + const res = [], path = []; + 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++ ) { + const n = candidates[i]; + if(n > target - sum) continue; + path.push(n); + sum += n; + backtracking(i, sum); + path.pop(); + sum -= n; + } } - if (i === hayslen - needlen) { - return -1; - } - } }; ```