39.Combination-Sum

39. Combination Sum

题目地址

https://leetcode.com/problems/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]
]

代码

Approach 1: backtracking

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

    List<Integer> combination = new ArrayList<>();
    Arrays.sort(candidates); // sort
    dfs(candidates, 0, target, combination, result);

    return result;
  }

  private void dfs(int[] candidates, int index, int target, List<Integer> combination, List<List<Integer>> result) {
    if (target == 0) {
      result.add(new ArrayList<Integer>(combination));
      return;
    }

    for (int i = index; i < candidates.length; i++) {
      if (candidates[i] > target) {
        break;
      }

      //  去重
      // if (i != 0 && candidates[i] == candidates[i - 1]) {
      //   continue;
      // } 

      combination.add(candidates[i]);
      dfs(candidates, i, target - candidates[i], combination, result);
      combination.remove(combination.size() - 1);
    }

  }
}

Approach #2 Reuse

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

    dfs(candidates, 0, target, new ArrayList<Integer>(), result);
    return result;
  }

  private void dfs(int[] candidates, int index, int target, List<Integer> combination, List<List<Integer>> result) {
    if (target == 0) {
      result.add(new ArrayList<Integer>(combination));
      return;
    }
    if (index == candidates.length || target < 0) {
      return;
    }

    dfs(candidates, index + 1, target, combination, result);

    if (index > 0 && candidates[index] == candidates[index - 1]) {
      return;
    }

    combination.add(candidates[index]);
    dfs(candidates, index, target - candidates[index], combination, result);
    combination.remove(combination.size() - 1);
  }

}

Last updated