使用 C++ 计算达到指定分数的方案数(只能使用 1 或 2 分,且不能连续使用 2 分)
给定一个得分。目标是以一种方式达到该得分,即击球手每次击球只能获得 1 分或 2 分。限制条件是不能连续获得 2 分。例如,要达到给定的得分 6,可以获得分数的方式如下:1+2+1+2,但不能是 2+2+1+1 或任何其他包含两个连续 2 的方式。
例如
输入
score=4
输出
Count of ways to reach a score using 1 and 2 with no consecutive 2s are: 4
解释
The ways in which we can reach the score 4 in following ways: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1
输入
score=5
输出
Count of ways to reach a score using 1 and 2 with no consecutive 2s are: 6
解释
The ways in which we can reach the score 6 in following ways: 1+1+1+1+1, 2+1+1+1, 1+2+1+1 , 1+1+2+1, 1+1+1+2, 2+1+2
以下程序中使用的方案如下 −
在这种方案中,我们将使用一个标志来标记前一个得分是否为 2,如果前一个得分是 2,我们将用下一个得分 1 来覆盖该得分,否则用 2 来覆盖。
取一个整数变量 score。
取标志变量 check,初始值为 false。
函数 ways_reach_score(int score, bool check) 用于计算使用 1 和 2 且不连续使用 2 来达到指定分数的方案数。
将初始计数设置为 0。
如果分数为 0,则返回 0。
如果 check 为 false,表示前一个得分是 1,因此,如果当前分数大于 0,则方案数将为 count = ways_reach_score(score − 1, false) + ways_reach_score(score − 2, true)。
否则,前一个得分是 2,因此后续得分只能是 1,所以方案数将为 ways_reach_score(score − 1, false)。
最后,我们将得到总方案数 count。
返回 count 作为结果。
示例
#include <bits/stdc++.h>
using namespace std;
int ways_reach_score(int score, bool check){
int count = 0;
if (score == 0){
return 1;
}
if (check == false && score > 1){
count += ways_reach_score(score − 1, false) + ways_reach_score(score − 2, true);
} else {
count += ways_reach_score(score − 1, false);
}
return count;
}
int main(){
int score = 4;
bool check = false;
cout<<"Count of ways to reach a score using 1 and 2 with no consecutive 2s are: "<<ways_reach_score(score, check);
return 0;
}输出
如果我们运行以上代码,它将生成以下输出:
Count of ways to reach a score using 1 and 2 with no consecutive 2s are: 4
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP