Combination Sum 39

Description

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

Hint

since it requires no duplicate combinations. so sort it firstly and then do DFS;

Method

one : backtracking (DFS) two : DP (like bag problem)

Time & Space

for one : o(n^high) for two : o(n ^3)

Code

one :

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

    public void DFSum(int[] candidates, int target,
                      List<List<Integer>> ans,
                      List<Integer> list,
                      int pos){
           if (target == 0){
               ans.add(new ArrayList<Integer>(list));
               return;
           }
           for (int i = pos; i < candidates.length; i++){
                if (candidates[i] > target){
                    return;
                }
                list.add(candidates[i]);
                DFSum(candidates, target - candidates[i], ans, list, i);
                list.remove(list.size() - 1);
           }
   }
}

Two : public List> combinationSum(int[] candidates, int target){ List>> dp = new ArrayList>>(); Arrays.sort(candidates); for (int i = 1; i <= target; i++){ List> list = new ArrayList>(); for (int j = 0; j < candidates.length && candidates[j] <= i; j++){ if (candidates[j] == i){ List sublist = new ArrayList(); sublist.add(candidates[j]); list.add(sublist); } else { for (List l : dp.get(i - candidates[j] - 1)){ if (candidates[j] <= l.get(0)){ List nl = new ArrayList(); nl.add(candidates[j]); nl.addAll(l); list.add(nl); } } }
} dp.add(list); } return dp.get(target - 1); }

results matching ""

    No results matching ""