经典动态规划:戳气球 :: labuladong的算法小抄 #1069
Replies: 7 comments 4 replies
-
DFS ver. class Solution {
public int maxCoins(int[] nums) {
int size = nums.length + 2;
int[] points = new int[size];
points[0] = 1;
points[size-1] = 1;
for(int i = 0; i < nums.length; i++) {
points[i+1] = nums[i];
}
int[][] memo = new int[size][size];
int result = dp(points, memo, 0, size-1);
// Arrays.stream(memo).map(Arrays::toString).forEach(System.out::println);
return result;
}
private int dp(int[] points, int[][] memo, int left, int right) {
// base case
if(left + 1 == right) {
return 0;
}
// continue
// memo check
if(memo[left][right] > 0) {
return memo[left][right];
}
// find max
int max = 0;
int pointsBase = points[left] * points[right];
for(int i = left + 1; i < right; i++) {
max = Math.max(
max,
points[i] * pointsBase
+ dp(points, memo, left, i)
+ dp(points, memo, i, right)
);
}
memo[left][right] = max;
return max;
}
} |
Beta Was this translation helpful? Give feedback.
-
既然dp[i][j]的定义是(i,j)开区间上的最大值,为什么不可以通过比较(i+1,j)区间的最大值加上戳破i+1得到的值和(i,j-1)区间的最大值加上戳破j-1得到的值来推算出dp[i][j]的值? |
Beta Was this translation helpful? Give feedback.
-
请问i为什么是 n -> 0遍历呢, 我试了 n+2 -> 0也是ok的 |
Beta Was this translation helpful? Give feedback.
-
看了文章,还是不太懂为什么i的遍历规则是n->0,为啥不是0->n。 |
Beta Was this translation helpful? Give feedback.
-
摘抄自leetcode.cn
|
Beta Was this translation helpful? Give feedback.
-
Py3 version: class Solution:
def maxCoins(self, nums: List[int]) -> int:
n = len(nums)
ballons = [1]+nums+[1]
dp = [[0]*(n+2) for _ in range(n+2)]
for i in range(n, -1, -1):
for j in range(i+1, n+2, 1):
res = 0
for k in range(i+1, j):
res = max(res, dp[i][k] + dp[k][j] + ballons[i] * ballons[k] * ballons[j])
dp[i][j] = res
return dp[0][n+1] |
Beta Was this translation helpful? Give feedback.
-
文章链接点这里:经典动态规划:戳气球
评论礼仪 见这里,违者直接拉黑。
Beta Was this translation helpful? Give feedback.
All reactions