11package Solution
22
3+ import "math"
4+
35func coinChange (coins []int , amount int ) int {
46 dp := make ([]int , amount + 1 )
57 for i := 0 ; i < amount + 1 ; i ++ {
@@ -11,6 +13,7 @@ func coinChange(coins []int, amount int) int {
1113 for j := 0 ; j < len (coins ); j ++ {
1214 if coins [j ] <= i {
1315 dp [i ] = min (dp [i ], dp [i - coins [j ]]+ 1 )
16+
1417 }
1518 }
1619 }
@@ -26,3 +29,54 @@ func min(x, y int) int {
2629 }
2730 return x
2831}
32+
33+ //动态规划(不压缩空间)
34+ func coinChange2 (coins []int , amount int ) int {
35+ dp := make ([][]int , len (coins )+ 1 ) //定义状态
36+ for i := 0 ; i <= len (coins ); i ++ {
37+ dp [i ] = make ([]int , amount + 1 )
38+ }
39+ //初始条件
40+ for j := 0 ; j <= amount ; j ++ {
41+ dp [0 ][j ] = amount + 1
42+ }
43+ dp [0 ][0 ] = 0
44+ for i := 1 ; i <= len (coins ); i ++ {
45+ for j := 0 ; j <= amount ; j ++ {
46+ //状态转移方程
47+ if j >= coins [i - 1 ] {
48+ dp [i ][j ] = int (math .Min (float64 (dp [i - 1 ][j ]), float64 (dp [i ][j - coins [i - 1 ]]+ 1 )))
49+ } else {
50+ dp [i ][j ] = dp [i - 1 ][j ]
51+ }
52+ }
53+ }
54+ if dp [len (coins )][amount ] > amount {
55+ return - 1
56+ } else {
57+ return dp [len (coins )][amount ]
58+ }
59+ }
60+
61+ //动态规划(压缩空间)
62+ func coinChange3 (coins []int , amount int ) int {
63+ dp := make ([]int , amount + 1 )
64+ //初始值
65+ for i := 0 ; i <= amount ; i ++ {
66+ dp [i ] = amount + 1
67+ }
68+ dp [0 ] = 0
69+
70+ for i := 1 ; i <= len (coins ); i ++ {
71+ for j := 0 ; j <= amount ; j ++ {
72+ if j >= coins [i - 1 ] {
73+ dp [j ] = int (math .Min (float64 (dp [j ]), float64 (dp [j - coins [i - 1 ]]+ 1 )))
74+ }
75+ }
76+ }
77+ if dp [amount ] > amount {
78+ return - 1
79+ } else {
80+ return dp [amount ]
81+ }
82+ }
0 commit comments