动态规划专题(笔记)

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
相关推荐
电鱼智能的电小鱼1 小时前
基于电鱼 AI 工控机的智慧工地视频智能分析方案——边缘端AI检测,实现无人值守下的实时安全预警
网络·人工智能·嵌入式硬件·算法·安全·音视频
孫治AllenSun2 小时前
【算法】图相关算法和递归
windows·python·算法
charlie1145141912 小时前
CSS笔记4:CSS:列表、边框、表格、背景、鼠标与常用长度单位
css·笔记·学习·css3·教程
格图素书3 小时前
数学建模算法案例精讲500篇-【数学建模】DBSCAN聚类算法
算法·数据挖掘·聚类
tjsoft3 小时前
汇通家具管理软件 1.0 试用笔记
笔记
DashVector4 小时前
向量检索服务 DashVector产品计费
数据库·数据仓库·人工智能·算法·向量检索
AI纪元故事会4 小时前
【计算机视觉目标检测算法对比:R-CNN、YOLO与SSD全面解析】
人工智能·算法·目标检测·计算机视觉
夏鹏今天学习了吗4 小时前
【LeetCode热题100(59/100)】分割回文串
算法·leetcode·深度优先
卡提西亚4 小时前
C++笔记-10-循环语句
c++·笔记·算法
还是码字踏实4 小时前
基础数据结构之数组的双指针技巧之对撞指针(两端向中间):三数之和(LeetCode 15 中等题)
数据结构·算法·leetcode·双指针·对撞指针