栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode-312. Burst Balloons [C++][Java]

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode-312. Burst Balloons [C++][Java]

LeetCode-312. Burst Balloonshttps://leetcode.com/problems/burst-balloons/

题目描述

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.

Example 1:

Input: nums = [3,1,5,8]
Output: 167
Explanation:
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins =  3*1*5    +   3*5*8   +  1*3*8  + 1*8*1 = 167

Example 2:

Input: nums = [1,5]
Output: 10

Constraints:

n == nums.length1 <= n <= 3000 <= nums[i] <= 100

解题思路 【C++】 1. 分治递归
class Solution {
public:
    vector> dp;
    int solve(int i,int j,vector& nums){
        if (i + 1 == j) {return 0;}
        if (dp[i][j] != -1) {return dp[i][j];}
        int ans = 0;
        for (int k = i + 1; k < j; k++){
            if (dp[i][k] == -1) {dp[i][k] = solve(i, k, nums);}
            if (dp[k+1][j] == -1) {dp[k][j] = solve(k, j, nums);}
            ans = max(ans, dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j]);
        }
        return dp[i][j] = ans;
    }

    int maxCoins(vector& nums) {
        nums.insert(nums.begin(), 1);
        nums.push_back(1);
        int n = nums.size();
        dp = vector>(n, vector(n, -1));
        return solve(0, n-1, nums);
    }
};
2. 动态规划
class Solution {
public:
    int maxCoins(vector& nums) {
       int n = nums.size();
       vector> dp(n, vector(n));
       for(int g = 0; g < n; g++){
           for(int i = 0, j = g; j 
【Java】 
class Solution {
    public int maxCoins(int[] nums) {
        int n = nums.length;
        if (n==0) return 0;
        if (n==1) return nums[0];
        int[][] memo = new int[n][n];
        for (int len=1; len<=n; len++) {
            for (int st=0,end=st+len-1; end 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/769904.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号