最小路径和---序列DP

题目

给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。

说明:每次只能向下或者向右移动一步。

思路

代码

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        if (grid.size() == 0 || grid[0].size() == 0) {
            return 0;
        }
        int rows = grid.size(), columns = grid[0].size();
        auto dp = vector < vector <int> >(rows, vector <int>(columns));
        dp[0][0] = grid[0][0];
        for (int i = 1; i < rows; i++) {
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }
        for (int j = 1; j < columns; j++) {
            dp[0][j] = dp[0][j - 1] + grid[0][j];
        }
        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < columns; j++) {
                dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }
        return dp[rows - 1][columns - 1];
    }
};

vector<int> split(string params_str) {
    vector<int> p;
    while (params_str.find(",") != string::npos) {
        int found = params_str.find(",");
        p.push_back(stoi(params_str.substr(0, found)));
        params_str = params_str.substr(found + 1);
    }
    p.push_back(stoi(params_str));
    return p;
}

vector<vector<int>> v;
vector<int> p;
vector<vector<int>> split_2_dimention(string s) {
    s += "  ";//防止最后一个]后面没有元素所导致的越界
    while (s.find("]") != string::npos) {
        int found_right = s.find("]");
        string s1 = s.substr(1, found_right - 1);
        p = split(s1);
        v.push_back(p);
        s = s.substr(found_right + 2);//取第二个vector,这里可能会越界
        p.clear();
    }
    return v;
}

int main() {
    string input;
    getline(cin, input);//[[1,3,1],[1,5,1],[4,2,1]]
    string input_str = input.substr(1, input.size() - 2);
    vector<vector<int>> dp;
    dp = split_2_dimention(input_str);
    Solution a;
    cout << a.minPathSum(dp);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值