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; }
}

  

最新文章

  1. 深入理解JavaScript的闭包特性如何给循环中的对象添加事件
  2. [tem]高精度2
  3. ubifs扩展性分析
  4. [原创]cocos2d-x研习录-第二阶 概念类之布场层类(CCLayer)
  5. C#:WebBrowser控件设置代理IP访问网站【附源码】
  6. HashMap原理详解
  7. Android Animation 动画属性
  8. android studio 报错,google后无果
  9. AMD的cpu如何安装Mac OS
  10. linux内核initrd文件自定义方法
  11. 认识 Linux 文件权限
  12. [转帖]K8H3D 病毒 腾讯御剑的解析
  13. shell 脚本使用记录
  14. 01 响应式页面-@media介绍,
  15. trie字典树
  16. JAVA面对对象(二)——继承、方法的覆写
  17. 序列化ADODataSet, ADOQuery
  18. jzoj5906
  19. 【idea】Error:java: Compilation failed: internal java compiler error 解决办法
  20. 前端必备的Nginx学习

热门文章

  1. [转帖]Reactor模式
  2. python实战项目 — 爬取 校花网图片
  3. bootstrap table 列表增加输入框并保存输入的值不清除
  4. 文件流CopyTo
  5. Ubuntu 18.04 LTS版本 谷歌拼音输入法安装
  6. Angular应用架构设计-3:Ngrx Store
  7. C语言的三套标准 C89(C90)、C99、C11
  8. vscode编辑器中文乱码问题
  9. ArrayList集合实现RandomAccess接口有何作用?为何LinkedList集合却没实现这接口
  10. 使用终端批量下载 B 站视频