Leetcode 39. Combination Sum

Description:

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

Thinking:

We use the comination template. But we should notice that the given array is a set, so there is no duplicated number. Then we don't need sort the array and we should note that the return condition is target == 0.

Step:

  1. check whether input is valid.
  2. create helper function. And decide the return condition.

    Code:

    public class Solution {
     public List<List<Integer>> combinationSum(int[] candidates, int target) {
         if(candidates == null || candidates.length == 0) return new ArrayList<List<Integer>>();
         List<List<Integer>> result = new ArrayList<>();
         List<Integer> list = new ArrayList<>();
         combinationSumHelper(result,list,candidates,target, 0);
         return result;
     }
     private void combinationSumHelper(List<List<Integer>> result, List<Integer> list, int[] candidates, int target, int pos){
         if(target == 0){
             result.add(new ArrayList<Integer>(list));
             return;
         }
         if(target < 0){
             return;
         }
         for(int i = pos; i < candidates.length; i++){
             list.add(candidates[i]);
             combinationSumHelper(result,list,candidates,target-candidates[i], i);
             list.remove(list.size()-1);
         }
     }
    }
    

    Conclusion:

    we should return whentarget < 0, to avoid stack overflow.

results matching ""

    No results matching ""