给定一个由不同整数构成的数组 nums 和一个整数 target ,请你从 nums 找出总和是 target 的组合的个数。解集中可以重复使用 nums 中的元素。且解集中数字顺序不同视为不同的组合。
数据范围: 数组长度满足 ,数组中的数满足 ,
[1,2,3],4
7
所有可能的组合为: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1)
[9],10
0
[9],18
1
[[9,9]]
function combination( nums , target ) { let res = 0; let path = []; nums.sort(); backTracking(nums, target, 0); return res; function backTracking(nums, target, sum){ if(sum === target){ res++; return; } if(sum > target){ return; } for(let i = 0; i < nums.length; i++){ sum += nums[i]; path.push(nums[i]); backTracking(nums, target, sum); sum -= nums[i]; path.pop(); } } }