动态规划 & 搜索_312.戳气球(20200719)

动态规划

// 1.定义 dp[i][j] 为区间 (i, j)内最大可获得硬币数
// 2.状态转移 —— 
// 		2.1 dp[i][j] = |k=i+1, j-1| max val[i]*val[k]*val[j] + dp[i][k] + dp[k][j] ,  i < j-1
// 		2.2 0 , i >= j - 1
// 3.base case :
// 		3.1 val[0] = val[n + 1] = 1;
// 4. ans = dp[0][n+1]
class Solution {
public:
    int maxCoins(vector<int>& nums) {
        int n = nums.size();
        int dp[n+2][n+2];
        int val[n+2]; // 修改原数组边界
        memset(dp, 0, sizeof(dp));
        memset(val, 0, sizeof(val));
        val[0] = val[n + 1] = 1;
        for (int i = 1; i <= n; i++) {
            val[i] = nums[i - 1];
        }
        for (int i = n - 1; i >= 0; i--) {
            for (int j = i + 2; j <= n + 1; j++) {
                for (int k = i + 1; k < j; k++) {
                    int sum = val[i] * val[k] * val[j];
                    sum += dp[i][k] + dp[k][j];
                    d[i][j] = max(rec[i][j], sum);
                }
            }
        }
        return rec[0][n + 1];
    }
};

记忆化搜索

// 常规搜索会超时
class Solution {
public:
    vector<vector<int>> rec;
    vector<int> val;

public:
    int solve(int left, int right) {
        if (left >= right - 1) {
            return 0;
        }
        if (rec[left][right] != -1) {
            return rec[left][right];
        }
        for (int i = left + 1; i < right; i++) {
            int sum = val[left] * val[i] * val[right];
            sum += solve(left, i) + solve(i, right);
            rec[left][right] = max(rec[left][right], sum);
        }
        return rec[left][right];
    }

    int maxCoins(vector<int>& nums) {
        int n = nums.size();
        val.resize(n + 2);
        for (int i = 1; i <= n; i++) {
            val[i] = nums[i - 1];
        }
        val[0] = val[n + 1] = 1;
        rec.resize(n + 2, vector<int>(n + 2, -1));
        return solve(0, n + 1);
    }
};

你可能感兴趣的:(Miracle,wandering,in,LeetCode)