Combination Sum 135

Question

Given a set of candidate numbers (C) 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.

For example, given candidate set 2,3,6,7 and target 7,

A solution set is:

[7]

[2, 2, 3]

Notice

All numbers (including target) will be positive integers.

Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).

The solution set must not contain duplicate combinations.

Solution

与Subsets类似。注意几点:

1) 每加入一个数,就要把下一层的targte为原来的targte减去这个数

2) 需要考虑避免重复:对元素排序,判断是否和前一个数等值

3) 可以重复取相同元素,所以下一层的起始pos和上一层相同

代码如下:

public class Solution {
    /**
     * @param candidates: A list of integers
     * @param target:An integer
     * @return: A list of lists of integers
     */
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        // write your code here
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if(candidates == null || candidates.length == 0 || target <= 0){
            return result;
        }

        ArrayList<Integer> list = new ArrayList<Integer>();
        Arrays.sort(candidates);
        helper(result, list, candidates, target, 0);

        return result;
    }

    private void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int[] candidates, int target, int pos){
        if(target == 0){
            result.add(new ArrayList<Integer>(list));
            return;
        }

        for(int i = pos; i < candidates.length; i++){
            if(i != 0 && candidates[i] == candidates[i - 1]){
                continue;
            }

            if(candidates[i] > target){
                return;
            }
            list.add(candidates[i]);
            helper(result, list, candidates, target - candidates[i], i);
            list.remove(list.size() - 1);
        }
    }
}

results matching ""

    No results matching ""