0312.cpp (796B)
1 class Solution { 2 public: 3 int maxCoins(vector<int> &nums) const { 4 nums.insert(begin(nums), 1); 5 nums.push_back(1); 6 7 const int n = size(nums); 8 static int dp[303][303]; 9 10 // dp[i][j]: coins obtained from bursting all the balloons between index i and j (not including i or 11 // j) dp[i][j] = max(nums[i] * nums[k] * nums[j] + dp[i][k] + dp[k][j]) (k in (i+1,j)) 12 13 memset(dp, 0x00, sizeof(dp)); 14 for (int d = 2; d < n; d++) { 15 for (int l = 0; l < n - d; l++) { 16 const int r = l + d; 17 for (int k = l + 1; k < r; k++) { 18 dp[l][r] = max(dp[l][r], nums[l] * nums[k] * nums[r] + dp[l][k] + dp[k][r]); 19 } 20 } 21 } 22 23 return dp[0][n - 1]; 24 } 25 };