unique-paths I &II 路径数,动态规划
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
class Solution { public: int uniquePaths(int m, int n) { int path[m][n]; for(int i=0;i<m;++i) path[i][0]=1; for(int i=0;i<n;++i) path[0][i]=1; for(int i=1;i<m;++i) { for(int j=1;j<n;++j) { path[i][j]=path[i-1][j]+path[i][j-1]; } } return path[m-1][n-1]; } };
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as1and0respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[ [0,0,0], [0,1,0], [0,0,0] ]
The total number of unique paths is2.
Note: m and n will be at most 100.
有障碍物的地方不能走,循环内加判断
class Solution { public: int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { int m=obstacleGrid.size(); int n=obstacleGrid[0].size(); int path[m][n]; for(int i=0;i<m;++i) { for(int j=0;j<n;++j) { if(obstacleGrid[i][j]==1) { path[i][j]=0; continue; } if(i==0&&j==0){ path[i][j]=1; continue; } if(i==0) { path[i][j]=path[i][j-1]; } else if(j==0){ path[i][j]=path[i-1][j]; } else{ path[i][j]=path[i-1][j]+path[i][j-1]; } } } return path[m-1][n-1]; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2017-09-12 批量部署 自动化之 - [pssh](转)
2017-09-12 malloc、calloc、realloc的区别(转)
2017-09-12 随机抽样一致性算法(RANSAC)