LeetCode 312. Burst Balloons

A very interesting question!

Think that we have N balloons to shot.

0 - 1 - 2 .... - n-1  in order to get the best score, we want to shot a special balloon, name it as k.

Then, we can get that.

0 - 1- 2 ... - k-1,  K, k+1 - k+2 ... n-1

Thus, the bestCoins we can get by shotting K is: bestCoins(0, k-1) + coins(K) + bestCoins(k+1, n-1).

Be careful that  bestCoins(0, k-1) and bestCoins(k+1, n-1) means that we know which balloons to shot and have been shot.

Coins(K) means : nums[k] * nums[i-1] * nums[j+1].


BitTiger said it is better to solve DP problem using visualization. Let's visualize this problem.

we cab choose to shot any balloon as a start, thus, we can visualize the process as follows:


From the picture, we can see that the time complexity is O(2^n). And, there is no way to pre-cache some data since every state is different. To better visualize the tree, let's draw it in this way:



Thus, if we see the above tree upside down, we can find the overlapped problem



The red number is the number every time's shot. We can clearly see the overlapped problem.

#include <vector>
#include <iostream>
using namespace std;

int maxCoins(vector<int>& nums) {
  /*
    suppose we use dp[i][j] to stand for maxCoins from (index i to index j)
    And, the best shoting index is k.
    Thus, dp[i][j] = dp[i][k-1] + dp[k+1][j] + nums[i-1]*nums[k-1]*nums[j+1];
    0 <= i < n; i <= j < n; i <= k <= j
  */
  int N = nums.size();
  nums.insert(nums.begin(), 1);
  nums.insert(nums.end(), 1);
  int n = nums.size();
  vector< vector<int> > dp(n, vector<int>(n, 0));

  //  This len variable trick is also pretty important.
  for(int len = 1; len <= N; ++len) {
    for(int start = 1; start <= N - len + 1; ++start) {
      int end = start + len - 1;
      int bestCoins = 0;
      for(int k = start; k <= end; ++k) {
        int coins = dp[start][k - 1] + dp[k + 1][end];
        coins += nums[start - 1] * nums[k] * nums[end + 1];
        if(coins > bestCoins) bestCoins = coins;
      }
      dp[start][end] = bestCoins;
    }
  }
  return dp[1][N];
}

int main(void) {
  vector<int> nums{3, 1, 5, 8};
  cout << maxCoins(nums) << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值