[LeetCode 39] Combination Sum (medium)

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. Base Case: sum == target,找到一组combination,返回。
  2. 如果没有找到,(题目已知 all numbers are positive), ==> 只有如果当 sum < target时,才继续找。
  3. 用找combination的思路:1. include self ; 2. exclude self,只是只有当 sum < target时,才继续找。
  4. 因为题目说:相同的数字可以重复使用,所以include self,在combinationEntry add self以后,迭代下一个时,继续从相同的数字开始。
    Note: 记得清楚状态
class Solution {
    public List> combinationSum(int[] candidates, int target) {
        List> result = new LinkedList<> ();
        if (candidates == null || candidates.length == 0) {
            return result;
        }
        
        List combinationEntry = new LinkedList<> ();
        
        combinationSumHelper (candidates, result, combinationEntry, target, 0, 0);
        
        return result;
    }
    
    private void combinationSumHelper (int[] candidates,
                                  List> result,
                                  List combinationEntry,
                                  int target,
                                  int sum,
                                  int currentIndex) {
        if (sum == target) {
            result.add (new ArrayList<> (combinationEntry));
            return;
        }
        
        // prune branches, only execute the following code if sum < target
        if (sum < target && currentIndex < candidates.length) {
            // include itself
            combinationEntry.add (candidates [currentIndex]);
            combinationSumHelper (candidates, result, combinationEntry, target, sum + candidates [currentIndex], currentIndex);
            combinationEntry.remove (combinationEntry.size () - 1);
            
            // exclude itself
            combinationSumHelper (candidates, result, combinationEntry, target, sum, currentIndex + 1);
        }
    }
    
}

你可能感兴趣的:([LeetCode 39] Combination Sum (medium))