动态规划专题(笔记)

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
相关推荐
丰锋ff22 分钟前
考研英一学习笔记
笔记·学习·考研
雾月5532 分钟前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
Invinciblenuonuo1 小时前
FreeRTOS学习笔记【10】-----任务上下文切换
笔记·学习
美味的大香蕉1 小时前
Spark-SQL与Hive
笔记
_Hello_Panda_1 小时前
FX10(CYUSB4014)USB3.2(10Gbps)开发笔记分享(1):硬件设计与开发环境搭建
笔记·fpga开发·fx10·cyusb4014
知来者逆2 小时前
计算机视觉——速度与精度的完美结合的实时目标检测算法RF-DETR详解
图像处理·人工智能·深度学习·算法·目标检测·计算机视觉·rf-detr
时间之城2 小时前
笔记:记一次使用EasyExcel重写convertToExcelData方法无法读取@ExcelDictFormat注解的问题(已解决)
java·spring boot·笔记·spring·excel
阿让啊2 小时前
C语言中操作字节的某一位
c语言·开发语言·数据结构·单片机·算法
এ᭄画画的北北2 小时前
力扣-160.相交链表
算法·leetcode·链表
灏瀚星空2 小时前
用Obsidian四个插件打造小说故事关联管理系统:从模板到图谱的全流程实践
经验分享·笔记·开源