算法题.
输入参数:(小数数组,总和)
输出参数:小数二维数组
要求:从输入的小数数组中找出所有和为输入的总和的组合
例子输入([1,2,3,4],6)输出[[1,2,3],[2,4]]
import copy
input_L = [1,2,3,4]
result = []
global tmp_answer
tmp_answer = []
def solve(input_L,res_sum,tmp_answer):
print input_L,res_sum,tmp_answer,'\n\n'
#满足条件,输出结果
if res_sum == 0:
x = sorted(copy.deepcopy(tmp_answer))
if x in result:
return
else:
result.append(x)
#不满足条件,返回
elif res_sum <0 or len(input_L) == 0:
#tmp_answer.pop()
return
for i in range(0, len(input_L)):
d = input_L[i]
#1 取第i个做为组合
tmp_answer.append(d)
input_L.pop(i)
#2 获取 res_sum-d 的组合结果
solve(input_L,res_sum-d,tmp_answer)
#3 放回i个
tmp_answer.pop()
input_L.append(d)
solve(input_L,6,tmp_answer)
print result
1 package main 2 3 import "fmt" 4 5 type loc struct { 6 n int 7 i int 8 } 9 10 var cache = make(map[loc][][]int) 11 12 func main() { 13 n := 6 14 vals := []int{1, 2, 3, 4} 15 t := f(n, len(vals)-1, vals) 16 fmt.Printf("%v\n", t) 17 } 18 19 func f(n, i int, vals []int) (ret [][]int) { 20 defer func() { 21 cache[loc{n, i}] = ret 22 }() 23 t := cache[loc{n, i}] 24 if t != nil { 25 return t 26 } 27 if i < 0 { 28 return [][]int{} 29 } 30 var t1, t2 [][]int 31 if n == vals[i] { 32 t1 = [][]int{{vals[i]}} 33 } 34 if n > vals[i] { 35 t1 = f(n-vals[i], i-1, vals) 36 for k, v := range t1 { 37 t1[k] = append(v, vals[i]) 38 } 39 } 40 t2 = f(n, i-1, vals) 41 return append(t1, t2...) 42 }
go语言
http://stackoverflow.com/a/10629938/523533
改改就好
感觉应该是DP算法解题吧。
经典背包问题