先看题目
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.
题目翻译: 给一个数组C和一个目标值T, 找出所有的满足条件的组合:使得组合里面的数字之和等于T,并且一些数字可以从C中午先选择。
注意:
-
所有给定的数字均为正整数.(这意味着我们加corner case invalid check的时候要加一条,如果给定T不是正整数,我们就没必要在往下进行了)
-
所有的答案组中要满足升序排列.
-
最后的答案数组不能包含重复答案.
注意一点,这里给出的数组里面数字不是重复的。
解决思路:采取递归的思想。我们先将数组从小到大排列一下,这样结果才符合题意。如何递归呢,我们先从第一个数字开始,用T减去这第一个数字,结果记为
T1,再从数组的第二数字开始,看剩下的这些数字加起来是否会等于T1,依次递归。
下面是代码,有几个细节要注意!
import java.util.*;
public class Solution {
public ArrayList
> combinationSum(int[] candidates, int target) {
ArrayList
> m=new ArrayList
>();//不要创建全局变量,因为多次测试会保存上次结果,导致ac不了 ArrayList
M=new ArrayList
(); Arrays.sort(candidates); DFS(m,M,0,candidates,target); return m; } public void DFS(ArrayList
> m,ArrayList
M,int index,int []can,int sum){ if(sum==0){ m.add(new ArrayList
(M));//注意要新建一个ArrayList return ; } if(sum<0) return ; for(int i=index;i