39. Combination Sum

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set [2, 3, 6, 7] and target 7
A solution set is: 

[ [7], [2, 2, 3] ]

 此题的思路可参考「数组的子集」:https://www.cnblogs.com/MarkLeeBYR/p/16887119.html

public List<List<Integer>> combinationSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
Arrays.sort(nums);
backtrack(list, temp, nums, target, 0);
return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> temp, int [] nums, int remian, int start) {
if (remian < 0)
return;
else if (remian == 0) {
list.add(new ArrayList<>(temp));
return;
}
for (int i = start; i < nums.length; i++) {
temp.add(nums[i]);
backtrack(list, temp, nums, remian - nums[i], i); //不是i加1,因为可以重复的用元素, 和其他回溯问题的区别:不能传start,必须是i。因为不能走“回头路”,比如2,3,5,target=7,选完3之后,第二轮不会再回过头来选2了
temp.remove(temp.size() - 1);
}
}
posted @   MarkLeeBYR  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示