LintCode 476. Stone Game (区间类DP经典题!重要!)

【Leetcode】动态规划分类总结 一 接龙型动态规划 题目一般是告诉你一个接龙规则,让你找最长的“龙”。 解题要点有两个: (1)要把「接龙规则」提炼并表示出来 (2)需要用“倒推法”(通常是写一个getPath()函数),获取最长‘龙’的具体方案。这就往往需要一个与dp[i]唯独相同的数组prev[i]记录,是哪个j(j 代表题目: Leetcode#300. Longest Increasing Subsequence Lintcode#398. Longest Continuous Increasing Subseque 阅读详情
  1. Stone Game

There is a stone game.At the beginning of the game the player picks n piles of stones in a line.

The goal is to merge the stones in one pile observing the following rules:

At each step of the game,the player can merge two adjacent piles to a new pile.
The score is the number of stones in the new pile.
You are to determine the minimum of the total score.

Example
Example 1:

Input: [3, 4, 3]
Output: 17
Example 2:

Input: [4, 1, 1, 4]
Output: 18
Explanation:

  1. Merge second and third piles => [4, 2, 4], score = 2
  2. Merge the first two piles => [6, 4],score = 8
  3. Merge the last two piles => [10], score = 18

先看一种错误的DP解法:错误在于
maxSum = max(maxSum, dp[i][k] + dp[k + 1][j]);
这个是不够的,因为还没有加上i和j之间的sum。光靠dp[i][i]和dp[i][i+1]的预处理不足以得到该sum。

class Solution {
public:
    /**
     * @param A: An integer array
     * @return: An integer
     */
    int stoneGame(vector<int> &A) {
        int n = A.size();
        if (n == 0) return 0;
        
        vector<vector<int>> dp(n, vector<int>(n, 0));
        
        for (int i = 0; i < n - 1; ++i) {
            dp[i][i] = A[i];
            dp[i][i + 1] = A[i] + A[i + 1];
        }
        dp[n - 1][n - 1] = A[n - 1];
        for (int i = 0; i < n - 1; ++i) {
            for (int j = 0; j < n; ++j) {
                int maxSum = 0;
                for (int k = i + 1; k < j; ++k) {
                    maxSum = max(maxSum, dp[i][k] + dp[k + 1][j]);
                }
                dp[i][j] = maxSum;
            }
        }
        
        return dp[0][n - 1];
    }
};

解法1:区间型DP。这道题的一个难点就是合并的过程中,A数组会变,所以DP过程中不能再用到A[i]。我们事先先把sums数组算好,这样A[i]变也没关系了。另外, dp[i][j]和sum[i]的坐标都是针对最初的数组。

这道题是一道区间dp的入门题,通过理解状态转移的过程来决定循环的要素。我们需要先枚举区间长度,再枚举起点。这就是区间dp的精髓。

dp[i][j]表示merge从i到j的stones的分数。

以输入[3,4,3]为例,最终dp[][]结果是:
0 7 17
0 0 7
0 0 0
我们可以看出,实际上这个DP算法只算了上半部的dp[][]值。dp[i][i]都没算。但是 这已经够了,我们只需要得到dp[0][n - 1]。
dp[][]计算顺序
dp[0][1], dp[1][2], dp[2][3], … , dp[n-2][n-1] //主对角线上面的那条对角线
dp[0][2], dp[1][3], dp[2][4], … , dp[n-3][n-1] //再上面一条对角线
…
dp[0][n-1] //右上方顶点

代码如下:

class Solution {
public:
    /**
     * @param A: An integer array
     * @return: An integer
     */
    int stoneGame(vector<int> &A) {
        int n = A.size();
        if (n == 0) return 0;
        
        vector<vector<int>> dp(n, vector<int>(n, 0));
        vector<int> sums(n, 0);
        
        sums[0] = A[0];        
        for (int i = 1; i < n; ++i) {
            sums[i] = sums[i - 1] + A[i];  
        }
        
        for (int len = 1; len <= n; ++len) {
            for (int i = 0; i + len < n; ++i) {
                dp[i][i + len] = INT_MAX;
                int sum = sums[i + len] - sums[i - 1];
                for (int k = i; k < i + len; ++k) {
                    dp[i][i + len] = min(dp[i][i + len], dp[i][k] + dp[k + 1][i + len] + sum);
                }
            }
        }

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

二刷:

class Solution {
public:
    /**
     * @param a: An integer array
     * @return: An integer
     */
    int stoneGame(vector<int> &a) {
        int n = a.size();
        if (n == 0) return 0;
        vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
        a.insert(a.begin(), 0);
        vector<int> sums(n + 1, 0);
        for (int i = 1; i <= n; i++) {
            sums[i] = sums[i - 1] + a[i];
        }
        for (int len = 1; len <= n; len++) {
            for (int i = 1; i + len <= n; i++) {
                int j = i + len;
                int sum = sums[j] - sums[i - 1];
                dp[i][j] = INT_MAX;
                for (int k = i; k < j; k++) {
                    dp [i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum);
                }
            }
        }
        return dp[1][n];
    }
};

上面把dp[][]初始化为0, 但在循环内又将其初始化为INT_MAX。不好想。其实关键是dp[i][i]的初始化,可以将dp[i][i]初始化为0,其他元素初始化为无穷大即可。因为一个元素的合并值为0。

class Solution {
public:
    /**
     * @param a: An integer array
     * @return: An integer
     */
    int stoneGame(vector<int> &a) {
        int n = a.size();
        if (n == 0) return 0;
        vector<vector<int>> dp(n + 1, vector<int>(n + 1, INT_MAX));
        a.insert(a.begin(), 0);
        //a.push_back(0);
        vector<int> sums(n + 1, 0);
        for (int i = 1; i <= n; i++) {
            sums[i] = sums[i - 1] + a[i];
        }
        for (int i = 0; i <= n; i++) dp[i][i] = 0;
        for (int len = 1; len <= n; len++) {
            for (int i = 1; i + len <= n; i++) {
                int j = i + len;
                int sum = sums[j] - sums[i - 1];
                //dp[i][j] = INT_MAX;
                for (int k = i; k < j; k++) {
                    dp [i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum);
                }
            }
        }
        return dp[1][n];
    }
};

解法2: DP + 递归

class Solution {
public:
    /**
     * @param A: An integer array
     * @return: An integer
     */
    int stoneGame(vector<int> &A) {
        int n = A.size();
        if (n == 0) return 0;
        
        dp.resize(n, vector<int>(n, 0));
        visited.resize(n, vector<bool>(n, false));
        presums.resize(n, vector<int>(n, 0));
        
        for (int i = 0; i < n - 1; ++i) {
            presums[i][i] = A[i];
            for (int j = i + 1; j < n; ++j) {
                presums[i][j] = presums[i][j - 1] + A[j];
            }
        }
        
        return search(0, n - 1);
    }
    
private:
    int search(int start, int end) {
        if (visited[start][end]) return dp[start][end];
        if (start == end) {
            visited[start][end] = true;
            return dp[start][end];
        }
        dp[start][end] = INT_MAX;
        for (int i = start; i < end; ++i) {
            dp[start][end] = min(dp[start][end], search(start, i) + search(i + 1, end) + presums[start][end]);
        }
        visited[start][end] = true;
        return dp[start][end];
    }
    vector<vector<int>> presums;
    vector<vector<bool>> visited;
    vector<vector<int>> dp;
};

二刷: 不需要visited数组,实际上sols[][]不为INT_MAX就说明已经处理过了。

class Solution {
public:
    /**
     * @param a: An integer array
     * @return: An integer
     */
    int stoneGame(vector<int> &a) {
        int n = a.size();
        if (n == 0) return 0;
        sums.resize(n + 1, 0);
        a.insert(a.begin(), 0);
        vector<vector<int>> sols(n + 1, vector<int>(n + 1, INT_MAX));
        for (int i = 1; i <= n; i++) {
            sums[i] = sums[i - 1] + a[i];
        }
        return helper(a, 1, n, sols);
    }
private:
    vector<int> sums;
    int helper(vector<int> &a, int start, int end, vector<vector<int>> &sols) {
        int ret = INT_MAX;
        if (start >= end) {
            return 0;
        }
        if (sols[start][end] != INT_MAX) return sols[start][end];
        int sum = sums[end] - sums[start - 1];
        for (int i = start; i <= end; i++) {
            sols[start][end] = min(sols[start][end],
                                   helper(a, start, i, sols) + helper(a, i + 1, end, sols) + sum);
        }
        return sols[start][end];
    }
};
Win10内网离线安装NET3.5,绝对成功,保姆级 今天工作安装工具软件套装3.5组件!也在csdn上找了很多方法躺了很多坑,我总结如下! 其实就一条,什么版本的win10装什么版本的net3.5 我的电脑是1909版本,用2004H2的镜像是没有用的,dism组件报错8024402C 所以我下载1909镜像挂在虚拟光驱 ,管理员模式下powershell dism.exe /online /enable-feature /featurename:NetFX3 /Source:E:\sources\sxs dism.exe /online /en.. 阅读详情

相关推荐

导航系统中坐标系介绍

日常开发中常用到八大坐标系: 1. 惯性坐标系 圆心是地球的原点,Z轴沿地轴方向朝向北极, X轴和Y轴位于赤道平面内,与Z轴满足右手法则,并且X轴和Y轴分别指向两个恒星。也就是说不随着地球的自转而发生变化。它是一个非常固定的坐标系。IMU测量得到的加速度,角速度都是相对于这个坐标系的。 特点:xy不动,不随着地球的自转而转动,可以作为地球附近传感器输出的惯性坐标系。 在导航中,有: 载体在导航系下的角速度 = 载体相对惯性系的角速度 – 导航系相对于惯性系的角速度 2. 地球坐标系 地球坐标系用oxey

xiaojinger_123的博客 7758

Leetcode(每日一题)——1140. 石子游戏 II

两人交替拿石子,为了在 i 尽量小的情况下,使 M 尽量大,那么每次都拿满M堆,最后有(2+4+8+⋯+M)+2M

庄小焱 648

C#:WPF格式转Winform格式

WPF格式转Winform格式

Hello C++ 1298

1140. Stone Game II (DP, DFS)

The DFS solution is quite intuitive and more like an implementation. Try to think in this way, every time you can either choose X piles, and this X would affect the latter decisions. And as both Alice and Bobs would make decisions optimally. We need to re

weixin_58286631的博客 291

RK3506开发板实战:5分钟搞定开源鸿蒙OpenHarmony5.1+星闪功能配置

本文提供了一份基于RK3506开发板快速配置开源鸿蒙OpenHarmony 5.1并启用星闪功能的实战指南。文章详细介绍了从开发环境搭建、系统镜像编译烧录,到星闪驱动加载验证、应用开发及性能调优的全流程,帮助开发者高效上手,将新一代短距无线通信技术应用于物联网项目。

time3的博客 677

倒立摆入门详解+pid调参

倒立摆制作全过程 最近在练习pid的控制算法,就选用了2013年的电子设计国赛题目:倒立摆 。 首先给你们看看我的成果 注意哦:倒立摆不是靠上面黄色的传感器保持平衡的,而是通过下面的电机左右扭动使得摆杆不掉下来,难度可不小了。 材料准备 1.机械部分 如图所示选好电机和角位移传感器进行组装就好了,这个部分是我直接网上购买的,如果要自己装也是可以的,不过会比较麻烦,结构差不多的。 2.主控部分 这个部分的话完全是我自己设计的,作用和网上买的一样,因为网上买的话太贵了,有需要的话可以联系我,有pcb文件

small_po_kid的博客 2万+

leetcode 1140. Stone Game II(石头游戏II)

game theory, dp, dfs

蓝羽飞鸟的博客 1033

【win11】主板更新之后pin不可用,恢复方法

台式机的主板更新了BIOS,再开机竟然登录不进去系统了。 登录界面上显示:【由于此设备上的安全设置已更改,你的pin码不再可用。单击以重新设置pin】 点击【单击以重新设置pin】没有任何反应。 也没有密码登录选项。 在网上找到解决方法,不用PE,只需要按步骤操作即可。通过实际验证可行,现记录如下。

1万+

1140. Stone Game II

https://leetcode.com/problems/stone-game-ii/ Alexand Lee continue theirgames with piles of stones. There are a number ofpilesarranged in a row, and each pile has a positive integer number of stonespiles[i]. The objective of the game is to end with...

Young's Blog 239

解决[WARN] : Controller Spawner couldn‘t find the expected controller_manager ROS interface.思路

rrbot例程ros_control配置问题的解决思路 本人刚入门ROS机器人开发,在学习rrbot例程出现了control_manager无法启动的bug。 在启动rrbot_control.launch的时候,出现下列warning: [WARN] [1594362016.372059]: Controller Spawner couldn't find the expected controller_manager ROS interface. 之后再按教程的步骤 rosservice call /

qq_40299650的博客 1万+

老款 NUC 复活计划:装 Ubuntu 部署 OpenClaw 本地 AI

老款 NUC 变身本地 AI 服务器指南 本文详细介绍了如何将老旧华硕 NUC 设备改造为本地 AI 服务器。主要内容包括: 硬件评估:列出老款 NUC 的最低配置要求(i3 6代/8GB内存/256GB SSD),并提供兼容性检查命令和性能预期表 系统准备:指导备份数据、下载 Ubuntu 22.04 LTS 和制作启动盘的方法(Windows/Linux双平台) 安装流程:从 BIOS 设置到 Ubuntu 安装的完整步骤,包括推荐的分区方案 系统优化:禁用不必要的服务、内核参数调优、Swap 配置和

博客 7627

LintCode 593: Stone Game II (DP经典题!)

Stone Game II There is a stone game.At the beginning of the game the player picks n piles of stones in a circle. The goal is to merge the stones in one pile observing the following rules: At each st...

roufoo的博客 1142

2025华为OD机试真题最新题库 (B+C+D+E+2025A+2025B卷) + 在线OJ在线刷题使用(C++、Java、Python C语言 JS合集)(正在更新2025B卷,目前已收录710道)

2024年,华为目前已经启用D卷,目前D卷和C卷的题目一样一次订阅永久阅读,支持在线刷题,持续更新,有问题随时解答,本专栏题目数量已收录到484道。每篇文章的思路分析都非常详细,题目新增图解思路,问题解疑,多样例测试,超过百字的思路参考解析。

KJ.JK 11万+

【Lintcode】476. Stone Game

题目地址: 给定一个数组,代表一列石头的重量。允许对相邻的两个石头合并,花费的能量是两个石头的重量之和。合并后,这两堆石头化成一堆,位置仍然在原位。现在需要将这列石头两两合并,直到合并成为一个石头,问所花费的最小能量是多少。 这是一道区间DP问题,我们需要用区间表示状态来递推。设sss是表示石头重量的数组,设f[i][j]f[i][j]f[i][j]是将s[i,...,j]s[i,...,j]s[...

数学、算法爱好者的博客 288

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

#476 Stone Game

题目描述: There is a stone game.At the beginning of the game the player picks n piles of stones in a line. The goal is to merge the stones in one pile observing the following rules: At each s

易水居 1114

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

【LeetCode】877. Stone Game 解题报告(Python & C++)

【LeetCode】877. Stone Game 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/stone-game/descriptio...

负雪明烛 3126

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

LeetCode 877. Stone Game(简单DP)

Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal. Example 1: Input: s1 = "sea", s2 = "eat" Output: 231 Explanation: Deleting "s" from "sea" adds the ...

qq_26973089的博客 233

[lintcode] Stone Game

There is a stone game.At the beginning of the game the player picksnpiles of stones in a line. The goal is to merge the stones in one pile observing the following rules: At each step of the game,t...

leetcode 解题思路 265

[Swift]LeetCode1140. 石子游戏 II | Stone Game II

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/streng...

weixin_30855761的博客 402

4387 Stone Game

#这是一道找规律的题。#问题Stone GameTime Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 943    Accepted Submission(s): 399Problem Description  Alice and Bob are...

u014302425的博客 357

Stone game

31.91% 3000ms 262144K CSL loves stone games. He hasnnstones; each has a weighta_iai​. CSL wants to get some stones. The rule is that the pile he gets should have a higher or equ...

weixin_30612769的博客 220

4388 Stone Game II

#博弈论的问题基本上是同一种想法——找规律。往往是通过很特殊的情况往一般情况衍生,或者说分析出特殊情况的必胜状态,一般情况往特殊情况靠拢。#还有特别使用到的是二进制,许多问题的分类都借助了二进制的优势,不论怎样表述的物品,比如格子、石头堆,二进制可以自动分类形成2^0,2^1等堆,在这种情况下进行异或操作有着天然的优势。#对于这道题而言,发现规律:所有石头数量的奇偶性与石头堆数的奇偶性异或,如果为...

u014302425的博客 1101

Lintcode 1667.石头

题目大意:一条直线上有n个石头,一个人从左往右走,碰到奇数块石头(碰到一块石头数一个数,这里指数的数是奇数),就往右扔,碰到偶数的石头就不管他,如果两块石头在同一个位置,就扔大的那块(能扔的距离小的)。问最后最远的那块石头的位置。 思路:用优先队列模拟,每遇到奇数石头,就将其坐标加上D[i],放回优先队列,当石头重叠时,先扔投大的(能扔的距离小的),故在比较函数中,以位置为第一关键字,以投掷距离...

sinat_33150417的博客 698

互联网大厂最常见的面试算法题大集合

点击上方“何俊林”,马上关注,每天早上8:50准时推送真爱,请置顶或星标很多朋友在后台留言,说是否有刷题总结,鱼哥从github上了解到一份不错的刷题集合记录,分享给大家...

欢迎关注公众号:【码农突围】,回复9999,可以获取一份LeetCode刷题笔记 2373

LC.1140. Stone Game II

class Solution(object): def stoneGameII(self, piles): """ 博弈问题,helper函数返回的是逆差,即当前选手能比下个选手多得多少分 每一层递归即每一位选手的选择都是最优化的,所以在第一步的时候第一位选手返回一个最大值即可 """ from functo...

很吵请安静 344

LINTCODE:438 找到字符串中所有的字母异位词(Python语言实现)

题目描述 给定一个字符串s和一个非空字符串p,找到s中所有是p的字母异位词的子串,返回这些子串的起始索引。 字符串只包含小写英文字母,并且字符串s和p的长度都不超过20100。 说明 字母异位词指字母相同,但排列不同的字符串。 不考虑答案输出的顺序。 示例1 输入: s: "cbaebabacd" p: "abc" 输出: [0, 6] 解释: 起始索引等于0的子串是"cba",它是"...

王山山 327
上一篇: LintCode 593: Stone Game II (DP经典题!)
下一篇: LintCode 396: Coins in a Line III (博弈类DP经典题)
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址