#递归机器人走步数
存在多个单元格,current表示现在所处的单元格,n表示单元格格数,aim表示目标单元格,rest表示剩余步数,求当剩余步数为0时,机器人能到达aim的方法数;
#include<stdio.h>
int way(int n,int current,int rest,int aim);
int main()
{
int n,current,aim,rest;
scanf("%d %d %d %d",&n,¤t,&rest,&aim);
int number=way(n,current,rest,aim);
printf("%d",number);
return 0;
}
int way(int n,int current,int rest,int aim)
{
if(rest==0)
{
return current==aim?1:0;
}
if(current==1)
{
return way(n,current+1,rest-1,aim);
}
if(current==n)
{
return way(n,current-1,rest-1,aim);
}
return way(n,current+1,rest-1,aim)+way(n,current-1,rest-1,aim);
}
由暴力递归到动态规划;
有的子问题重复,可将此子问题记录下来,下次能够用到
#include<stdio.h>
int way(int n, int current, int rest, int aim, int dp[][rest+1]);
int main() {
int n, current, rest, aim, i, j;
scanf("%d %d %d %d", &n, ¤t, &rest, &aim);
int dp[n+1][rest+1];
for (i = 1; i <= n; i++) {
for (j = 0; j <= rest; j++) {
dp[i][j] = -1;
}
}
int num = way(n, current, rest, aim, dp);
printf("%d", num);
return 0;
}
int way(int n, int current, int rest, int aim, int dp[][rest]) {
if (dp[current][rest] != -1) {
return dp[current][rest];
}
int ans = 0;
if (rest == 0) {
ans = current == aim ? 1 : 0;
} else {
if (current == 1) {
ans = way(n, current+1, rest-1, aim, dp);
} else if (current == n) {
ans = way(n, current-1, rest-1, aim, dp);
} else {
ans = way(n, current-1, rest-1, aim, dp) + way(n, current+1, rest-1, aim, dp);
}
}
dp[current][rest] = ans;
return ans;
}
记忆化搜索,从顶向下的动态规划
再进行优化