当前位置:网站首页>动态规划问题 - 小兵向前冲
动态规划问题 - 小兵向前冲
2022-07-17 00:13:00 【想做程序媛的小太阳】
题目描述:
N*M的棋盘,小兵从左下角走到右上角,只能向上或向右走,问有多少种走法?
解答:
解法一:
public static int trace(int m, int n) {
if(n < 1 || m < 1)
return 0;
if(n == 1 && m == 1)
return 1;
return trace(m - 1, n) + trace(m, n - 1);
}时间复杂度:2^(n + m)
解法二:
public static int trace(int m, int n) {
int[][] num = new int[m + 1][n + 1];
if(n < 1 || m < 1) {
return 0;
}
if(n == 1 && m == 1) {
num[1][1] = 1;
return num[1][1];
}
if(num[m][n] > 0) {
return num[m][n];
}
else {
num[m][n] = trace(m - 1, n) + trace(m, n - 1);;
return num[m][n];
}
}时间复杂度:m*n
问题扩展:
1. 如果某些格子禁止小兵进入,怎么处理?
public static int trace(int m, int n, int m0, int n0) {
int[][] num = new int[m + 1][n + 1];
if(n < 1 || m < 1) {
return 0;
}
if(n == 1 && m == 1) {
num[1][1] = 1;
return num[1][1];
}
if(n == n0 && m == m0){
num[m][n] = 0;
return num[m][n];
}
if(num[m][n] > 0) {
return num[m][n];
}
else {
num[m][n] = trace(m - 1, n) + trace(m, n - 1);;
return num[m][n];
}
}2. 如果小兵在一个方向上可以走一步或两步?
//假设在m方向上可以走一步或两步
public static int trace(int m, int n) {
int[][] num = new int[m + 1][n + 1];
if(n < 1 || m < 1) {
return 0;
}
if(n == 1 && m == 1) {
num[1][1] = 1;
return num[1][1];
}
if(num[m][n] > 0) {
return num[m][n];
}
else if(m <= 2)
{
num[m][n] = trace(m - 1, n) + trace(m, n - 1);
return num[m][n];
}
else{
num[m][n] = trace(m - 1, n) + trace(m, n - 1) + trace(m - 2,n);
return num[m][n];
}
}
边栏推荐
- Oozie integrated sh
- Problems encountered in yolov3 training its own data set
- MATLAB :Warning: the font “Times” is not available
- Hands on deep learning -- multi layer perceptron (MLP)
- Double Q-Learning理论基础及其代码实现【Pendulum-v0】
- Build map reduce development environment
- 基于蒙特卡洛的强化学习方法【附带代码实现】
- Owl Eyes: Spotting UI Display Issues via Visual Understanding
- The code of dsaa related articles in the blog
- 工程编译那点事:Makefile和cmake(一)
猜你喜欢

06基于STM32的智能电子药盒设计

ResNet

06 design of smart electronic medicine box based on stm32

bais mintigation post-processing for individual and group fairness

03基于ZigBee的城市道路除尘降温系统设计

Fair Attribute Classification through Latent Space De-biasing

IEEE754标准浮点数格式

04 design of indoor wireless positioning system based on ZigBee

gdb+vscode进行调试0——环境配置

Compilation and link of C language program
随机推荐
Owl Eyes: Spotting UI Display Issues via Visual Understanding
Build Ozzie environment
06基于STM32的智能电子药盒设计
Allegro design entry CIS and OrCAD capture CIS relationship
05 design of street lamp control fault detection system based on ZigBee
CMake常用命令
switch详解
Original code, inverse code, complement code
芝诺悖论2 阿基里斯与乌龟
LeetCode:动态规划中的多重背包问题【一个模板解决所有~】
原码,反码,补码
SABER 最强大的数模混合信号仿真软件
成信大ENVI_IDL第二周课堂内容:打开HDF4文件并读取文件以及简单的数据处理和保存+详细解析
gdb+vscode进行调试0——环境配置
Hue oozie editor scheduling shell
Build map reduce development environment
指针常量与常量指针爱恨情仇
Saber Pspice simulink电源仿真软件的区别
成信大ENVI_IDL第三周课堂内容1:读取OMI数据(HDF5文件)以及输出+解析
04基于ZigBee的室内无线定位系统设计