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] ]

Solution

public class Solution {
      public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        solve(candidates, 0, target, 0, new ArrayList<>(), result);
        return result;
    }

    private void solve(int[] candidates, int pos, int target, int runner, List<Integer> current, List<List<Integer>> result) {
        if (runner > target) {
            return;
        } else if (runner == target) {
            result.add(new ArrayList<>(current));
        } else {

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

                current.add(candidates[i]);
                solve(candidates, i, target, runner + candidates[i], current, result);
                current.remove(current.size() - 1);
            }
        }
    }
}

results matching ""

    No results matching ""