leetcode 486. Predict the Winner

Gold_stein發表於2024-10-03

leetcode 486. Predict the Winner

class Solution {
   public:
    bool predictTheWinner(vector<int>& nums) {
        int m = nums.size();
        // f[i][j]表示(i,j)區間上,先手能超過後手多少分
        std::vector<std::vector<int>> f(m, std::vector<int>(m));
        for (int i = 0; i < m; i++) f[i][i] = nums[i];
        for (int len = 2; len <= m; len++)
            for (int i = 0; i + len - 1 < m; i++) {
				int j = i + len - 1;
                f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]);
            }
        return f[0][m - 1] >= 0;
    }
};

可以記錄每個狀態是怎麼轉移過來的,然後reverse一下,就得到最優方案了

相關文章