public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
List<Integer> ret = new ArrayList<Integer>();
dfs(candidates, target, ret, list, 0);
return list;
}
private static void dfs(int[] nums, int target, List<Integer> ret, List<List<Integer>> list, int begin)
{
if (target == 0)
{
list.add(new ArrayList(ret));
return;
}
for (int i = begin; i < nums.length; i++)
{
while (i > begin && i < nums.length && nums[i] == nums[i-1])
i++;
if (i == nums.length || target - nums[i] < 0)
break;
ret.add(nums[i]);
dfs(nums, target-nums[i], ret, list, i+1); // 减去当前值,下一个计算从i+1开始,而不是从现在的i开始计算
ret.remove(ret.size()-1);
}
}
【LeetCode 40】组合总和
最新推荐文章于 2024-09-02 13:36:46 发布