weinan030416

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

拿石子dp

每次从一开始或者最后拿,拿多的赢

复制代码
#include<iostream>
using namespace std;

int stone[10];
int dp[10][10];//从i到j两人数量差的最大值
 
int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    cin>>stone[i];
    for(int i=0;i<n;i++)
    dp[i][i]=stone[i];
    for (int i = n - 2; i >= 0; i--)
            for (int j = i + 1; j < n; j++)
                dp[i][j] = max(stone[i] - dp[i + 1][j], stone[j] - dp[i][j - 1]);
    cout<<dp[0][n - 1];
} 
复制代码

 一维数组

复制代码
class Solution {
public:
    bool stoneGame(vector<int>& piles) {
        int length = piles.size();
        auto dp = vector<int>(length);
        for (int i = 0; i < length; i++) {
            dp[i] = piles[i];
        }
        for (int i = length - 2; i >= 0; i--) {
            for (int j = i + 1; j < length; j++) {
                dp[j] = max(piles[i] - dp[j], piles[j] - dp[j - 1]);
            }
        }
        return dp[length - 1] > 0;
    }
};

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/stone-game/solution/shi-zi-you-xi-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
复制代码

 

posted on   楠030416  阅读(8)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示