用两种颜色(红色和黄色)粉刷楼梯,使得相邻的楼梯不能都是黄色的 C++ 方法
假设我们有 n 个台阶,以及两种颜色(红色和黄色)来粉刷这些台阶。我们的任务是计算可以粉刷这些台阶的方法数量,使得没有两个连续的台阶是黄色的。
让我们举个例子来理解这个问题,
输入
3
输出
5
解释
The ways in which stairs can be painted are YRY, RYR, YRR, RRY, RRR. here R denotes red color, Y denotes yellow color.
为了解决这个问题,让我们看看粉刷这些台阶的方法数量。
N = 1,方法(1) = 2:R,Y
N = 2,方法(2) = 3:RY,YR,RR
N = 3,方法(3) = 5:RYR,YRY,RRY,YRR,RRR
N = 4,方法(4) = 8:YRYR,RYRY,RYRR,YRRY,YRRR,RRYR,RRRR,RRRY。
所以从这些例子中,我们可以推导出这是一个斐波那契数列,以 2 作为第一个元素,3 作为第二个元素。
程序来说明我们逻辑的工作原理,
示例
#include <iostream>
using namespace std;
int colorSteps(int n) {
int first = 2;
int next = 3;
for (int i = 3; i <= n; i++) {
next = first + next;
first = next - first;
}
return next;
}
int main(){
int n = 6;
cout<<"Number of ways to color "<<n<<" steps is "<<colorSteps(n);
return 0;
}输出
Number of ways to color 6 steps is 21
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP