LeetCode 64. 最小路径和
打了一天游戏,没时间学习,要努力辽。
今天只是刷了一题leetcode,暂时以动态规划 相关题型为复习点,编点工程代码。
新建./include/Solution.h
cpp
#include <vector>
using namespace std;
class Solution {
public:
int minPathSum(vector<vector<int>> &grid);
};
新建./source/Solution.cpp
cpp
#include <vector>
#include <algorithm>
#include "Solution.h"
using namespace std;
int Solution::(vector<vector<int>> &grid) {
int rows = grid.size();
int cols = grid[0].size();
auto dp = vector<vector<int>> (rows, vector<int> (cols));
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 i = 1; i < cols; i++) {
dp[0][i] = dp[0][i-1] + grid[0][i];
}
for(int i = 1; i < rows; i++) {
for(int j = 1; j < cols; j++) {
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
}
}
return dp[rows - 1][cols - 1];
}
新建./main.cpp
cpp
#include <vector>
#include <iostream>
#include "Solution.h"
using namespace std;
int main(int argc, char **argv) {
int n,m;
cin >> n >> m;
auto grid = vector<vector<int>> (n, vector<int> (m));
for (auto i = 0; i < n; i++) {
for (auto j = 0; j < m; j++) {
cin >> grid[i][j];
}
}
Solution mySolution;
cout << mySolution.minPathSum(grid) <<endl;
return 0;
}
新建./CMakeLists.txt
cpp
#声明要求的cmake最低版本
cmake_minimum_required(VERSION 3.0)
#声明一个cmake工程
project(Solution)
include_directories(include)
#添加一个可执行程序
#语法:add_executable(程序名 源代码文件)
add_executable(main_cmake main.cpp source/Solution.cpp)
执行
cpp
mkdir build
cd build
cmake ..
make
./main_cmake
测试用例
cpp
3
3
1 3 1 1 5 1 4 2 1
测试结果
cpp
7