39. Combination Sum

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

The same repeated number may be chosen from candidates unlimited number of times.

Note:

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

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

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

Solution

(1) Java

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> rst = new ArrayList<>();
        Arrays.sort(candidates);
        helper(candidates, target, rst, new ArrayList<Integer>(), 0);
        return rst;
    }

    private void helper(int[] candidates, int target, List<List<Integer>> rst, List<Integer> list, int start) {
        if (target == 0) {
            rst.add(new ArrayList<Integer>(list));
            return;
        } else if (target < 0) {
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            list.add(candidates[i]);
            helper(candidates, target-candidates[i], rst, list, i);
            list.remove(list.size()-1);
        }
    }
}

(2) Python

class Solution:
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        dp = []
        for i in range(target+1):
            dp.append([])
        for i in range(1, target+1):
            for j in range(0,len(candidates),1):
                num = candidates[j]
                if i == num:
                    dp[i].append([num])
                    break
                elif i > num:
                    dpdp = dp[i-num]
                    for lt in dpdp:
                        if lt and num <= lt[0]:
                            lt2 = list(lt)
                            lt2.insert(0,num)
                            dp[i].append(lt2)
        return dp[target]

(3) Scala



results matching ""

    No results matching ""