Skip to content

Commit 97e5e1d

Browse files
hzslabuladong
authored andcommitted
【877.石子游戏【Python】
1 parent 8b8f413 commit 97e5e1d

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

动态规划系列/动态规划之博弈问题.md

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,4 +215,57 @@ int stoneGame(int[] piles) {
215215
<img src="../pictures/qrcode.jpg" width=200 >
216216
</p>
217217

218-
======其他语言代码======
218+
======其他语言代码======
219+
220+
221+
222+
223+
224+
python3版本
225+
226+
由[SCUHZS](https://github.com/brucecat)提供
227+
228+
这里采取的是三维的做法
229+
230+
```python
231+
class Solution:
232+
def stoneGame(self, piles: List[int]) -> bool:
233+
n = len(piles)
234+
235+
# 初始化一个n*n的矩阵 dp数组
236+
dp = [[None] * n for i in range(0, n)]
237+
238+
# 在三角区域填充
239+
for i in range(n):
240+
for j in range(i, n):
241+
dp[i][j] = [0, 0]
242+
243+
# 填入base case
244+
for i in range(0, n):
245+
dp[i][i][0] = piles[i]
246+
dp[i][i][1] = 0
247+
248+
# 斜着遍历数组
249+
for l in range(2, n + 1):
250+
for i in range(0, n-l+1):
251+
j = l + i - 1
252+
253+
254+
# 先手选择最左边或最右边的分数
255+
left = piles[i] + dp[i + 1][j][1]
256+
right = piles[j] + dp[i][j - 1][1]
257+
258+
# 套用状态转移方程
259+
if left > right:
260+
dp[i][j][0] = left
261+
dp[i][j][1] = dp[i + 1][j][0]
262+
else:
263+
dp[i][j][0] = right
264+
dp[i][j][1] = dp[i][j - 1][0]
265+
266+
res = dp[0][n - 1]
267+
268+
return res[0] - res[1] > 0
269+
270+
```
271+

0 commit comments

Comments
 (0)