leetcode 494. 目标和

题解

简单粗暴,直接根据上一次的结果存储各种可能性

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
func findTargetSumWays(nums []int, S int) int {
hash := make(map[int]int)
hash[0] = 1
for _, v := range nums {
tmp := make(map[int]int)
for k, _ := range hash {
tmp[k+v] += hash[k]
tmp[k-v] += hash[k]
}
hash = tmp
}
return hash[S]
}