天天看點

《leetcode-go》加起來和為目标值的組合

給出一組候選數 C 和一個目标數 T ,找出候選數中起來和等于 T 的所有組合。

C 中的每個數字在一個組合中隻能使用一次。

注意:

1. 題目中所有的數字(包括目标數 T )都是正整數

2. 組合中的數字 ( a1,a2,...,ak ) 要按非遞減排序 ( 

《leetcode-go》加起來和為目标值的組合

 ).

3. 結果中不能包含重複的組合

4. 組合之間的排序按照索引從小到大依次比較,小的排在前面,如果索引相同的情況下數值相同,則比較下一個索引。

資料範圍:

1<=n<=50

1<=target<=100

1<=C[i]<=50

思路:遞歸的方法,固定一個值,然後在這個值之後的裡面找可以的組合,重點需要注意的是遞歸怎麼把資料傳出來,還有臨時的tmp一定要是新定義的,要不然slice是共用的

package main
import "sort"
/**
 * 
 * @param num int整型一維數組 
 * @param target int整型 
 * @return int整型二維數組
*/
func combinationSum2(num []int, target int) [][]int {
	// write code here
	sort.Ints(num)
	res := make([][]int, 0)
	combination(num, 0, target, nil, &res)
	return res
}

func combination(num []int, start int, target int, tmp []int, res *[][]int) {
	if target <= 0 {
		if target == 0 {
			*res = append(*res, tmp)
		}
		return
	}
	for i := start; i < len(num); i++ {
		if num[i] <= target {
			if i > start && num[i] == num[i-1] {
				continue
			}
			newTmp := append([]int{}, tmp...)
			newTmp = append(newTmp, num[i])
			combination(num, i+1, target-num[i], newTmp, res)
		}
	}
}