递归练习题:骰子游戏(类似上楼梯,简单递归)

【问题描述】
玩家根据骰子点数决定走的步数,骰子为1走1步,为n走n步,现在要求玩家走到第n步时总共有多少种走法。
(1<= n <= 6)

比如n = 6
我们站在最后一次的角度上看,我们是可以0号位置掷6点直接到达,也可以从先掷1点再掷5点。。。总而言之,我只可能从n - 1, n - 2,。。。n - 6这六个位置一步到达

代码:

#include<iostream>
using namespace std;

int n;

int f(int x)
{
	if(x < 0)		//不合法的情况为0
		return 0;
	if(x == 0)
		return 1;
	return f(x - 1) + f(x - 2) + f(x - 3) + f(x - 4) + f(x - 5) + f(x - 6);
}

int main()
{
	cin >> n;
	cout << f(n) << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40163242/article/details/88027324