Description
tags : array, backtracking difficulty: medium
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.var results [][]int
var existed map[string]int
func combinationSum(candidates []int, target int) [][]int {
results = make([][]int, 0)
if len(candidates) == 0 {
return results
}
existed = make(map[string]int)
sort.Ints(candidates)
backtrack(candidates, target, nil)
return results
}
func backtrack(candidates []int, target int, result []int){
for _,val := range candidates {
if val == target {
result = append(result, val)
addIfNotExist(result)
break
}
if val < target {
result = append(result, val)
backtrack(candidates, target - val, result)
result = result[0:len(result) - 1]
continue
}
if val > target {
break
}
}
}
func addIfNotExist(result []int){
var cr []int
for _,val := range result {
cr = append(cr, val)
}
sort.Ints(cr)
var s string = ""
for _, val := range cr {
s += "," + string(val)
}
if _,ok := existed[s];ok {
return
}
results = append(results, cr)
existed[s] = 1
}Need to consider