0
点赞
收藏
分享

微信扫一扫

LeetCode_Array_312. Burst Balloons 戳气球【动态规划】【Java】【困难】


目录

​​一,题目描述​​

​​英文描述​​

​​中文描述​​

​​示例与说明​​

​​二,解题思路​​

​​三,AC代码​​

​​Java​​

​​四,解题过程​​

​​第一搏​​

 

一,题目描述

英文描述

You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.

If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.

Return the maximum coins you can collect by bursting the balloons wisely.

中文描述

有 n 个气球,编号为0 到 n - 1,每个气球上都标有一个数字,这些数字存在数组 nums 中。

现在要求你戳破所有的气球。戳破第 i 个气球,你可以获得 nums[i - 1] * nums[i] * nums[i + 1] 枚硬币。 这里的 i - 1 和 i + 1 代表和 i 相邻的两个气球的序号。如果 i - 1或 i + 1 超出了数组的边界,那么就当它是一个数字为 1 的气球。

求所能获得硬币的最大数量。

示例与说明

LeetCode_Array_312. Burst Balloons 戳气球【动态规划】【Java】【困难】_动态规划


二,解题思路

参考​​@狗大王【[这个菜谱, 自己在家也能做] 关键思路解释】​​

上面的题解中对于本题的核心思想介绍的非常清晰易懂!这里再简单记录一下。

1,对于开区间范围(i, j)内的每一个气球k,将气球k看作区间内最后一个戳爆的。用dp[i][j]记录开区间(i, j)内的最大得分。

2,这样dp[i][j] = dp[i][k] + nums[i] * nums[k] * nums[j] + dp[k][j]。

3,其中 dp[i][k] 和 dp[k][j] 可参照上面的思路递归求解。

LeetCode_Array_312. Burst Balloons 戳气球【动态规划】【Java】【困难】_困难_02

 

三,AC代码

Java

class Solution {
public int maxCoins(int[] nums) {
int newLen = nums.length + 2;
int[] newNums = new int[newLen];// 创建新数组,左右两边添加1,便于处理边界情况
newNums[0] = 1;
newNums[newLen - 1] = 1;
for (int i = 0; i < nums.length; i++) {
newNums[i + 1] = nums[i];
}

int dp[][] = new int[newLen][newLen];
int ans = getMaxCoins(newNums, 0, newLen - 1, dp);
return ans;
}

public int getMaxCoins(int[] nums, int left, int right, int[][] dp) {
for (int i = left + 1; i < right; i++) {
int leftVal = dp[left][i] == 0 ? getMaxCoins(nums, left, i, dp) : dp[left][i];// !!!不为0表示已经计算过该结果,可以直接使用,重新计算则会超时
int rightVal = dp[i][right] == 0 ? getMaxCoins(nums, i, right, dp) : dp[i][right];
int res = leftVal + nums[left] * nums[i] * nums[right] + rightVal;
dp[left][right] = Math.max(dp[left][right], res);
}
return dp[left][right];
}
}

四,解题过程

第一搏

看了大神的题解,豁然开朗,算法实现起来不是很复杂,注意边界就好

LeetCode_Array_312. Burst Balloons 戳气球【动态规划】【Java】【困难】_java_03

举报

相关推荐

0 条评论