leetcode1301 最大得分的路径数目

题目

题目

分析

老子要是以后还会踩背包问题的坑,老子就不是人!

代码

class Solution {
public:
    vector pathsWithMaxScore(vector& board) {

        if (board.empty()){
            return vector(2, 0);
        }

        int row = board.size();
        int col = board[0].size();
        int mod = pow(10, 9) + 7;

        vector dp(col, 0);
        vector dp2(col, 0);
        dp2[col - 1] = 1;

        for (int i = row - 1; i >= 0; i--){
            vector new_dp(col, 0);
            vector new_dp2(col, 0);
            if (i == row - 1){
                new_dp2[col - 1] = 1;
            }
            for (int j = col - 1; j >= 0; j--){
                //更新最大值
                if (board[i][j] == 'S' || board[i][j] == 'X'){
                    new_dp[j] = 0;
                }else if (board[i][j] == 'E'){
                    new_dp[j] = max(new_dp[j + 1], max(dp[j], dp[j + 1])) % mod;
                }else if (i == row - 1){
                    new_dp[j] = (new_dp[j + 1] + (board[i][j] - '0')) % mod;
                }else if (j == col - 1){
                    new_dp[j] = (dp[j] + (board[i][j] - '0')) % mod;
                }else{
                    new_dp[j] = (max(new_dp[j + 1], max(dp[j], dp[j + 1])) + (board[i][j] - '0')) % mod;
                }

                //找到到达这里最大值的路径的位置
                int pre_max;
                if (board[i][j] == 'E'){
                    pre_max = new_dp[j];
                }else{
                    pre_max = new_dp[j] - (board[i][j] - '0');
                }
                    
                //更新路径数
                if (j + 1 < col && new_dp[j + 1] == pre_max){
                    new_dp2[j] = (new_dp2[j] + new_dp2[j + 1]) % mod;
                }
                if (j + 1 < col && i + 1 < row && dp[j + 1] == pre_max){
                    new_dp2[j] = (new_dp2[j] + dp2[j + 1]) % mod;
                }
                if (i + 1 < row && dp[j] == pre_max){
                    new_dp2[j] = (new_dp2[j] + dp2[j]) % mod;
                }
            }
            dp = new_dp;
            dp2 = new_dp2;
        }      

        vector res;
        if (dp2[0] == 0){
            dp[0] = 0;
        }
        res.push_back(dp[0]);
        res.push_back(dp2[0]);

        return res;
    }
};

你可能感兴趣的:(leetcode1301 最大得分的路径数目)