LeetCode: Combination Sum 解题报告

Combination Sum

Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Question Solution
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.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
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]

SOLUTION 1:

经典递归模板。

i 的起始值是跟排列的最主要区别。因为与顺序无关,所以我们必须只能是升序,也就是说下一个取值只能是i本身或是i的下一个。
但是排列的话,可以再取前同的。1, 2 与2 1是不同的排列,但是同一个组合

同学们可以看下这几个题目的区别。

LeetCode: Letter Combinations of a Phone Number 解题报告

LeetCode: Permutations II 解题报告

LeetCode: Permutations 解题报告

LeetCode: Combinations 解题报告

 1 public class Solution {
 2     public List<List<Integer>> combinationSum(int[] candidates, int target) {
 3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
 4         if (candidates == null || candidates.length == 0) {
 5             return ret;
 6         }
 7         
 8         // Sort to avoid duplicate solutions.
 9         Arrays.sort(candidates);
10         
11         dfs(candidates, target, new ArrayList<Integer>(), ret, 0);
12         return ret;
13     }
14     
15     public void dfs(int[] candidates, int target, List<Integer> path, List<List<Integer>> ret, int index) {
16         if (target < 0) {
17             return;
18         }
19         
20         if (target == 0) {
21             ret.add(new ArrayList(path));
22             return;
23         }
24         
25         // i 的起始值是跟排列的最主要区别。因为与顺序无关,所以我们必须只能是升序,也就是说下一个取值只能是i本身
26         // 或是i的下一个。
27         // 但是排列的话,可以再取前同的。1, 2 与2 1是不同的排列,但是同一个组合
28         for (int i = index; i < candidates.length; i++) {
29             int num = candidates[i];
30             path.add(num);
31             
32             // 注意,最后的参数是i,不是index!!
33             dfs(candidates, target - num, path, ret, i);
34             path.remove(path.size() - 1);
35         }
36     }
37 }
View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/combination/CombinationSum_1203.java

原文地址:https://www.cnblogs.com/yuzhangcmu/p/4141175.html