使用递归和回溯
ts
function findSum(arr: number[],target:number,count:number):number[][] {
if(arr.length === 0 || count <= 0) return []
const answers: number[][] = []
const current: number[] = []
const backtrack = (start: number,sum: number,n: number) => {
if(sum === 0 && n === 0) {
answers.push([...current])
return
}
for(let i = start; i < arr.length; i++) {
if(arr[i] <= sum) {
current.push(arr[i])
backtrack(i + 1,sum-arr[i],n-1)
current.pop()
}
}
}
backtrack(0,target,count)
return answers
}