暴力递归与动态规划

#递归机器人走步数

存在多个单元格,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,&current,&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, &current, &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;
}

记忆化搜索,从顶向下的动态规划

再进行优化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值