public void testKNumEqualsTarget() {
Integer[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k = 3;
int target = 20;
List<List<Integer>> r = new ArrayList<>();
testKSum(new LinkedList<>(), nums, 0, k, target, 0, r);
System.out.println(JSON.toJSONString(r));
}
/***
* sum+=值
* @param path
* @param nums
* @param start
* @param k
* @param target
* @param sum
* @param r
*/
private void testKSum(LinkedList<Integer> path, Integer[] nums, int start, int k,
int target, int sum, List<List<Integer>> r) {
if (path.size() == k && sum == target) {
r.add(new ArrayList<>(path));
return;
}
for (int i = start; i < nums.length; i++) {
path.add(nums[i]);
sum += nums[i];
//下一次起始index = i+1
testKSum(path, nums, i + 1, k, target, sum, r);
path.removeLast();
sum -= nums[i];
}
}
无重复数列中Nsum问题
最新推荐文章于 2024-11-05 21:58:11 发布