LeetCode 40. Combination Sum II

题目描述

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

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

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]

解题思路

可以用典型的回溯法做。题目要求每次每个组合不可以重复,即2 3 4 和 4 2 3属于同一个组合,那么先要对输入数组进行排序。然后利用DFS依次往临时列表tmpList里面添加元素。如果tmpList元素之和刚好为target,则把tmpList加入到resList。如果和大于target,则回溯到上一层继续添加其他元素。

AC代码

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> resList = new ArrayList<>();
        Arrays.sort(candidates); //必要的操作,先对输入数组进行排序
        if(candidates == null || candidates.length == 0) return resList;
        backtrack(resList, new ArrayList<Integer>(), candidates, target, 0, 0);
        return resList;
    }

    /** resList:最终的结果list tmpList:当前添加进去的元素 candidates:输入元素数组 target:目标值 sum:当前tmpList元素之和 start:为了避免出现重复的组合,从start开始往后进行元素添加 */    

    private void backtrack(List<List<Integer>> resList, ArrayList<Integer> tmpList, int[] candidates, int target, int sum, int start){
        if(sum == target){
            resList.add(new ArrayList(tmpList));
            return;
        }
        for(int i = start;i < candidates.length;i++){
            if(sum + candidates[i] > target) return;
            if(i != start && candidates[i] == candidates[i - 1]) continue;
            sum += candidates[i];
            tmpList.add(candidates[i]);
            backtrack(resList, tmpList, candidates, target, sum, i + 1);
            tmpList.remove(tmpList.size() -1 );
            sum -= candidates[i];
        }
    }

}
点赞