📜  用两种颜色绘制楼梯以使相邻的两个都不是黄色的方法

📅  最后修改于: 2021-05-04 10:44:48             🧑  作者: Mango

给定n个楼梯,我们有两种颜色的黄色和绿色,任务是我们必须用给定的颜色绘制给定的楼梯,但条件是我们不能彼此直接直接绘制两个黄色台阶。

例子 :

Input : n = 1
Output : 2
A single stair can be colored either
as green or yellow.

Input : n = 3
Output : 5

情况1:楼梯只有1个时,我们可以涂成黄色或绿色。
情况2:当我们有2个楼梯时,我们可以用黄色或绿色来绘制第一个楼梯,但是对于下一个楼梯,我们只能用绿色来绘制,因为我们不能彼此直接直接绘制两个黄色台阶。因此,总共有三个YG,GG,GY。
情况3:当我们有3个楼梯时,我们可以用5种方法对其进行绘画。

如果我们仔细观察,我们会注意到它遵循斐波那契数列。

C++
// C++ Program to find the number of ways to paint stairs
#include 
using namespace std;
  
// Function to find the number of ways
int ways(int n)
{
    int W[n + 1];
  
    // take base case for 1 and 2
    W[1] = 2;
    W[2] = 3;
  
    for (int i = 3; i <= n; i++) 
        W[i] = W[i - 1] + W[i - 2];
      
    return W[n];
}
  
// Driven code
int main()
{
    int n = 3;
    printf("%d", ways(n));
    return 0;
}


Java
// java Program to find the number of
// ways to paint stairs
import java.io.*;
  
public class GFG {
      
    // Function to find the number of ways
    static int ways(int n)
    {
        int []W = new int[n+1];
      
        // take base case for 1 and 2
        W[1] = 2;
        W[2] = 3;
      
        for (int i = 3; i <= n; i++) 
            W[i] = W[i - 1] + W[i - 2];
          
        return W[n];
    }
      
    // Driven code
    static public void main (String[] args)
    {
        int n = 3;
          
        System.out.println(ways(n));
    }
}
  
// This code is contributed by vt_m.


Python3
# Python3 code to find the number
# of ways to paint stairs
  
# Function to find the number of ways
def ways( n ):
    W = list()
      
    # take base case for 1 and 2
    W.append(0)
    W.append(2)
    W.append(3)
      
    i = 3
    while i <= n:
        W.append(W[i - 1] + W[i - 2])
        i = i + 1
          
    return W[n]
  
# Driver code
n = 3
print(ways(n))
  
# This code is contributed by "Sharad_Bhardwaj".


C#
// C# Program to find the number of
// ways to paint stairs
using System;
  
public class GFG {
      
    // Function to find the number of ways
    static int ways(int n)
    {
        int []W =new int[n+1];
      
        // take base case for 1 and 2
        W[1] = 2;
        W[2] = 3;
      
        for (int i = 3; i <= n; i++) 
            W[i] = W[i - 1] + W[i - 2];
          
        return W[n];
    }
      
    // Driven code
    static public void Main ()
    {
        int n = 3;
      
        Console.WriteLine(ways(n));
    }
}
  
// This code is contributed by vt_m.


PHP


输出 :

5

时间复杂度: O(n)
额外空间: O(n)

我们也可以使用矩阵幂解的第n个斐波那契数,在O(Log n)时间内解决此问题。