486. 预测赢家(动态规划)

class Solution:
    def PredictTheWinner(self, nums: List[int]) -> bool:
        # @lru_cache()
        def dfs(i,j):
            if i==j:
                return nums[i]
            return max(nums[i]-dfs(i+1,j),nums[j]-dfs(i,j-1))
        return dfs(0,len(nums)-1)>=0
class Solution {
public:
    // int dfs(vector& nums, )
    bool PredictTheWinner(vector<int>& nums) {
        int n=nums.size();
        vector<vector<int>>dp(n,vector<int>(n,0));
        for(int i=0;i<n;i++)
        dp[i][i]=nums[i];
        for(int j=1;j<n;j++){
            for(int i=0;i<n-j;i++){
                dp[i][i+j]=max(nums[i]-dp[i+1][i+j],nums[i+j]-dp[i][i+j-1]);
            }

        }
        return dp[0][n-1]>=0;
    }
};

你可能感兴趣的:(leetcode)