题目链接:https://www.lintcode.com/problem/combination-sum-ii/description
/**
* @param num: Given the candidate numbers
* @param target: Given the target number
* @return: All the combinations that sum to target
*/
func combinationSum2(num []int, target int) [][]int {
// write your code here
var results [][]int = [][]int{};
if (num == nil || len(num) == 0) {
return results;
}
sort.Ints(num);
var combination []int;
helper(num, 0, combination, target, &results);
return results;
}
func helper(num []int, startIndex int, combination []int, target int, results *[][]int) {
if (target == 0) {
tmp := []int{};
tmp = append(tmp, combination...);
*results = append(*results, tmp);
//fmt.Println(results);
return;
}
var i int;
for i = startIndex; i < len(num); i++ {
//这一步没必要,是跑不到的,每一次重复元素又变成了新的头元素
if (i != startIndex && num[i] == num[i-1]) {
continue;
}
if (target < num[i]) {
break;
}
var addCom = append(combination, num[i]);
helper(num, i+1, addCom, target-num[i], results);
}
}
func main() {
var num1 []int = []int{7, 1, 2, 5, 1, 6, 10};
var target1 int = 8;
var combination1 [][]int = combinationSum2(num1, target1);
fmt.Println(combination1);
var num2 []int = []int{};
var target2 int = 1;
var combination2 [][]int = combinationSum2(num2, target2);
fmt.Println(combination2);
}