Medium
总分 >= 0
时表示先手获胜,反之,表示先手无法获胜python3
class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
@functools.lru_cache(None)
def helper(start,end):
if start == end:
return nums[start]
left = nums[start] - helper(start+1,end)
right = nums[end] - helper(start,end-1)
return max(left,right)
return helper(0,len(nums)-1) >= 0
记忆化递归通常可以转换成自底向上的动态规划方式来做
dp
数组,dp[i][j]
表示选择当前人作为先手的前提下在区间[i,j]
中,所能获得的最大相对分数i == j
时,表示只能选i
,值为nums[i]
dp[i][j] = max(nums[i]-dp[i+1][j], nums[j]-dp[i][j-1])
以上,尝试写一下代码,AC!
python3
class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
length = len(nums)
if length == 1:
return True
dp = [[0]*length for i in range(length)]
for i in range(length):
dp[i][i] = nums[i]
for m in range(1,length): #覆盖长度
for n in range(length-m): #i在该覆盖长度下的取值范围
dp[n][n+m] = max(nums[n]-dp[n+1][n+m],nums[n+m]-dp[n][n+m-1])
return dp[0][length-1]>=0