给你一个候选数字的集合(不含重复的数字)和一个目标数,找出候选集中所有唯一的组合数,其中组合数的
和为目标数。
同样的数字可以使用多次。
1. 回溯法
public List<List<Integer>> combinationSum(int[] candidates, int target)
{
// 存储符合条件的结果(二维列表)
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(candidates);
backtrack(list, new ArrayList<>(), candidates, target, 0);
return list;
}
private void backtrack(List<List<Integer>> list, List<Integer> tempList,
int [] nums, int remain, int start)
{
if (remain < 0)
return;
else if (remain == 0)
// 构造一个包含指定集合元素的列表
list.add(new ArrayList<>(tempList));
else
{
for (int i=start; i<nums.length; i++)
{
tempList.add(nums[i]);
// not i + 1 because we can reuse same elements
backtrack(list, tempList, nums, remain-nums[i], i);
tempList.remove(tempList.size()-1);
}
}
}