@@ -55,6 +55,37 @@ eg: 对于 [1,2,5] 组成 11 块
55
55
56
56
对于动态规划我们可以先画一个二维表,然后观察,其是否可以用一维表代替。
57
57
关于动态规划为什么要画表,我已经在[ 这篇文章] ( ../thinkings/dynamic-programming.md ) 解释了
58
+
59
+ 比较容易想到的是二维数组:
60
+
61
+ ``` python
62
+ class Solution :
63
+ def coinChange (self , coins : List[int ], amount : int ) -> int :
64
+ if amount < 0 :
65
+ return - 1
66
+ dp = [[amount + 1 for _ in range (len (coins) + 1 )]
67
+ for _ in range (amount + 1 )]
68
+ # 初始化第一行为0,其他为最大值(也就是amount + 1)
69
+
70
+ for j in range (len (coins) + 1 ):
71
+ dp[0 ][j] = 0
72
+
73
+ for i in range (1 , amount + 1 ):
74
+ for j in range (1 , len (coins) + 1 ):
75
+ if i - coins[j - 1 ] >= 0 :
76
+ dp[i][j] = min (
77
+ dp[i][j - 1 ], dp[i - coins[j - 1 ]][j] + 1 )
78
+ else :
79
+ dp[i][j] = dp[i][j - 1 ]
80
+
81
+ return - 1 if dp[- 1 ][- 1 ] == amount + 1 else dp[- 1 ][- 1 ]
82
+ ```
83
+
84
+ ** 复杂度分析**
85
+ - 时间复杂度:$O(amonut * len(coins))$
86
+ - 空间复杂度:$O(amount * len(coins))$
87
+
88
+ dp[ i] [ j ] 依赖于` dp[i][j - 1] ` 和 ` dp[i - coins[j - 1]][j] + 1) ` 这是一个优化的信号,我们可以将其优化到一维,具体见下方。
58
89
## 关键点解析
59
90
60
91
- 动态规划
@@ -120,35 +151,6 @@ public:
120
151
121
152
Python3 Code:
122
153
123
-
124
- (二维数组)
125
-
126
- ```python
127
- class Solution:
128
- def coinChange(self, coins: List[int], amount: int) -> int:
129
- if amount < 0:
130
- return - 1
131
- dp = [[amount + 1 for _ in range(len(coins) + 1)]
132
- for _ in range(amount + 1)]
133
- # 初始化第一行为0,其他为最大值(也就是amount + 1)
134
-
135
- for j in range(len(coins) + 1):
136
- dp[0][j] = 0
137
-
138
- for i in range(1, amount + 1):
139
- for j in range(1, len(coins) + 1):
140
- if i - coins[j - 1] >= 0:
141
- dp[i][j] = min(
142
- dp[i][j - 1], dp[i - coins[j - 1]][j] + 1)
143
- else:
144
- dp[i][j] = dp[i][j - 1]
145
-
146
- return -1 if dp[-1][-1] == amount + 1 else dp[-1][-1]
147
- ```
148
-
149
-
150
- (一维数组)
151
-
152
154
```python
153
155
class Solution:
154
156
def coinChange(self, coins: List[int], amount: int) -> int:
@@ -162,10 +164,16 @@ class Solution:
162
164
163
165
return -1 if dp[-1] == amount + 1 else dp[-1]
164
166
```
167
+
168
+ ** 复杂度分析**
169
+ - 时间复杂度:$O(amonut * len(coins))$
170
+ - 空间复杂度:$O(amount)$
171
+
172
+
165
173
## 扩展
166
174
167
175
这是一道很简单描述的题目, 因此很多时候会被用到大公司的电面中。
168
176
169
177
相似问题:
170
178
171
- [518 .coin-change-2 ](. /518 .coin-change-2 .md)
179
+ [518 .coin-change-2 ](https: // github.com/azl397985856/leetcode/blob/master/problems /518.coin-change-2.md)
0 commit comments