Stone Game II
2024-10-21 14:39:03
Description
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 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:
[1,1,4,4]
Output:18
Explanation:
1. Merge second and third piles => [2, 4, 4], score +2
2. Merge the first two piles => [6, 4],score +6
3. Merge the last two piles => [10], score +10
Example 2:
Input:
[1, 1, 1, 1]
Output:8
Explanation:
1. Merge first and second piles => [2, 1, 1], score +2
2. Merge the last two piles => [2, 2],score +2
3. Merge the last two piles => [4], score +4
思路:动态规划。
dp[i][j]代表从i合并到j的最少花费。
转移方程为dp[i][j] = min(dp[i][k] + dp[k+1][j] + sum[j + 1] - sum[i])
public class Solution {
/**
* @param A an integer array
* @return an integer
*/
public int stoneGame2(int[] A) {
// Write your code here
int n = A.length;
if (n <= 1)
return 0; int[][] dp = new int[2 * n][2 * n]; int[] sum = new int[2 * n + 1]; for (int i = 1; i <= 2 * n; ++i) {
sum[i] = sum[i - 1] + A[(i - 1) % n];
} for (int i = 0; i < 2 * n; ++i) {
dp[i][i] = 0;
} for(int len = 2; len <= 2 * n; ++len)
for(int i= 0;i < 2 * n && i + len - 1 < 2 * n; ++i) {
int j = i + len - 1;
dp[i][j] = Integer.MAX_VALUE;
for (int k = i; k < j; ++k) {
if (dp[i][k] + dp[k+1][j] + sum[j + 1] - sum[i] < dp[i][j])
dp[i][j] = dp[i][k] + dp[k+1][j] + sum[j + 1] - sum[i];
}
} int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; ++i)
if (dp[i][i + n - 1] < ans)
ans = dp[i][i + n - 1];
return ans; }
}
最新文章
- 深入理解JavaScript的闭包特性如何给循环中的对象添加事件
- [tem]高精度2
- ubifs扩展性分析
- [原创]cocos2d-x研习录-第二阶 概念类之布场层类(CCLayer)
- C#:WebBrowser控件设置代理IP访问网站【附源码】
- HashMap原理详解
- Android Animation 动画属性
- android studio 报错,google后无果
- AMD的cpu如何安装Mac OS
- linux内核initrd文件自定义方法
- 认识 Linux 文件权限
- [转帖]K8H3D 病毒 腾讯御剑的解析
- shell 脚本使用记录
- 01 响应式页面-@media介绍,
- trie字典树
- JAVA面对对象(二)——继承、方法的覆写
- 序列化ADODataSet, ADOQuery
- jzoj5906
- 【idea】Error:java: Compilation failed: internal java compiler error 解决办法
- 前端必备的Nginx学习