mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
@ -416,24 +416,31 @@ func backTree(n,k,startIndex int,track *[]int,result *[][]int){
|
|||||||
* @return {number[][]}
|
* @return {number[][]}
|
||||||
*/
|
*/
|
||||||
var combinationSum3 = function(k, n) {
|
var combinationSum3 = function(k, n) {
|
||||||
const backtrack = (start) => {
|
let res = [];
|
||||||
const l = path.length;
|
let path = [];
|
||||||
if (l === k) {
|
let sum = 0;
|
||||||
const sum = path.reduce((a, b) => a + b);
|
const dfs = (path,index) => {
|
||||||
if (sum === n) {
|
// 剪枝操作
|
||||||
|
if (sum > n){
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (path.length == k) {
|
||||||
|
if(sum == n){
|
||||||
res.push([...path]);
|
res.push([...path]);
|
||||||
|
return
|
||||||
}
|
}
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
for (let i = start; i <= 9 - (k - l) + 1; i++) {
|
for (let i = index; i <= 9 - (k-path.length) + 1;i++) {
|
||||||
path.push(i);
|
path.push(i);
|
||||||
backtrack(i + 1);
|
sum = sum + i;
|
||||||
path.pop();
|
index += 1;
|
||||||
|
dfs(path,index);
|
||||||
|
sum -= i
|
||||||
|
path.pop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let res = [], path = [];
|
dfs(path,1);
|
||||||
backtrack(1);
|
return res
|
||||||
return res;
|
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -328,13 +328,11 @@ var lowestCommonAncestor = function(root, p, q) {
|
|||||||
}
|
}
|
||||||
if(root.val>p.val&&root.val>q.val) {
|
if(root.val>p.val&&root.val>q.val) {
|
||||||
// 向左子树查询
|
// 向左子树查询
|
||||||
let left = lowestCommonAncestor(root.left,p,q);
|
return root.left = lowestCommonAncestor(root.left,p,q);
|
||||||
return left !== null&&left;
|
|
||||||
}
|
}
|
||||||
if(root.val<p.val&&root.val<q.val) {
|
if(root.val<p.val&&root.val<q.val) {
|
||||||
// 向右子树查询
|
// 向右子树查询
|
||||||
let right = lowestCommonAncestor(root.right,p,q);
|
return root.right = lowestCommonAncestor(root.right,p,q);
|
||||||
return right !== null&&right;
|
|
||||||
}
|
}
|
||||||
return root;
|
return root;
|
||||||
};
|
};
|
||||||
|
Reference in New Issue
Block a user