您的位置:首页 > 编程语言 > Java开发

LeetCode_39---Combination Sum

2015-06-18 11:42 483 查看
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]
 

Hide Tags
 Array Backtracking

翻译:

Code:

package From21;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author MohnSnow
* @time 2015年6月18日 上午9:44:22
* @result 递归方法和动态规划方法
*/
public class LeetCode39 {

/**
* @param argsmengdx
* -fnst
*/
//backtracking---326msA---http://www.1point3acres.com/bbs/thread-108008-1-1.html
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(candidates); // sort the array
recurse(new ArrayList<Integer>(), target, candidates, 0, result);
return result;
}

public static void recurse(List<Integer> list, int target, int[] candidates, int index, List<List<Integer>> result) {
if (target == 0) {
result.add(list);
return;
}
for (int i = index; i < candidates.length; i++) {
int newTarget = target - candidates[i]; // subtract candidate from target
if (newTarget >= 0) {
List<Integer> copy = new ArrayList<Integer>(list); // create a copy,include list
copy.add(candidates[i]);
recurse(copy, newTarget, candidates, i, result); // see if there is more
} else { // run out of target
break;
}
}
}

public static void main(String[] args) {
int[] candidates = { 1, 2, 3, 4, 6, 7, 9 };
int target = 7;
System.out.println("求和 : " + combinationSum(candidates, target).toString());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 LeetCode java