Count ways to reach a score using 1 and 2 with no consecutive 2s - GeeksforGeeks

28 Sep, 2021
A cricket player has to score N runs, with condition he can take either 1 or 2 runs only and consecutive runs should not be 2. Find all the possible combination he can take.Examples:  
Input : N = 4 
Output : 4
1+1+1+1, 1+2+1, 2+1+1, 1+1+2

Input : N = 5
Output : 6
Source :Oracle Interview On campus 
This problem is a variation of count number of ways to reach given score in a game and can be solved in O(n) time and constant auxiliary space.
First run scored could be either :
a) 1. Now the player has to score N-1 runs.
b) or 2. Since 2’s can not be consecutive runs, next run scored has to be 1. After that, the player has to score N-(2+1) runs.Below is the recursive solution of above problem. 
Recursion relation would be:
CountWays(N) = CountWays(N-1) + CountWays(N-2)
Following recursive solution takes exponential time and space (similar to Fibonacci numbers).  
C++
Java
Python3
C#
PHP
Javascript
// A simple recursive implementation for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed#include <iostream>using namespace std; int CountWays(int n){    // base cases    if (n == 0) {        return 1;    }    if (n == 1) {        return 1;    }    if (n == 2) {        return 1 + 1;    }     // For cases n > 2    return CountWays(n - 1) + CountWays(n - 3);} // Driver codeint main(){    int n = 10;    cout << CountWays(n);    return 0;}
// A simple recursive implementation for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed import java.io.*; class GFG {    static int CountWays(int n)    {        // base cases        if (n == 0) {            return 1;        }        if (n == 1) {            return 1;        }        if (n == 2) {            return 1 + 1;        }         // For cases n > 2        return CountWays(n - 1) + CountWays(n - 3);    }     // Driver code    public static void main(String[] args)    {        int n = 5;        System.out.println(CountWays(n));    }}
# A simple recursive implementation for# counting ways to reach a score using 1 and 2 with# consecutive 2 allowed  def CountWays(n):     # base case    if n == 0:        return 1    if n == 1:        return 1    if n == 2:        return 1 + 1     # For cases n > 2    return CountWays(n - 1) + CountWays(n - 3)  # Driver codeif __name__ == '__main__':    n = 5    print(CountWays(n))
// A simple recursive implementation// for counting ways to reach a score// using 1 and 2 with consecutive 2 allowedusing System; class GFG {    static int CountWays(int n)    {        // base cases        if (n == 0) {            return 1;        }        if (n == 1) {            return 1;        }        if (n == 2) {            return 1 + 1;        }         // For cases n > 2        return CountWays(n - 1) + CountWays(n - 3);    }     // Driver Code    static public void Main()    {        int n = 5;        Console.WriteLine(CountWays(n));    }}
<?php// A simple recursive implementation// for counting ways to reach a score// using 1 and 2 with consecutive 2 allowed function CountWays($n){    // base cases    if ($n == 0) {        return 1;    }    if ($n == 1) {        return 1;    }    if ($n == 2) {        return 1 + 1;    }       // For cases n > 2    return CountWays($n - 1) + CountWays($n - 3);} // Driver Code$n = 5;echo CountWays($n);?>
<script> // A simple recursive implementation for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed  function CountWays(n, flag){    // base cases    if (n == 0) {        return 1;    }    if (n == 1) {        return 1;    }    if (n == 2) {        return 1 + 1;    }       // For cases n > 2    return CountWays(n - 1) + CountWays(n - 3);} // Driver code let n = 5;document.write(CountWays(n, false)); </script>
6
 
We can store intermediate values and solve it in O(n) time and O(n) space. 
C++
Java
Python3
C#
Javascript
// Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed#include <iostream>using namespace std; int CountWays(int n){    // noOfWays[i] will store count for value i.    // 3 extra values are to take care of corner case n = 0    int noOfWays[n + 3];     noOfWays[0] = 1;    noOfWays[1] = 1;    noOfWays[2] = 1 + 1;         // Loop till "n+1" to compute value for "n"    for (int i=3; i<n+1; i++) {      noOfWays[i] =        // number of ways if first run is 1        noOfWays[i-1]        // number of ways if first run is 2        // and second run is 1        + noOfWays[i-3];    }    return noOfWays[n];} int main(){    int n = 0;    cout << CountWays(n);    return 0;}
import java.util.Arrays; // Bottom up approach for// counting ways to reach a score using// 1 and 2 with consecutive 2 allowedclass GfG {    static int CountWays(int n)    {        // noOfWays[i] will store count for value i.        // 3 extra values are to take care of cornser case n        // = 0        int noOfWays[] = new int[n + 3];         noOfWays[0] = 1;        noOfWays[1] = 1;        noOfWays[2] = 1 + 1;         // Loop till "n+1" to compute value for "n"        for (int i = 3; i < n + 1; i++) {            noOfWays[i] =                // number of ways if first run is 1                noOfWays[i - 1]                // number of ways if first run is 2                // and second run is 1                + noOfWays[i - 3];        }        return noOfWays[n];    }     public static void main(String[] args)    {        int n = 5;        System.out.println(CountWays(n));    }}
# Bottom up approach for# counting ways to reach a score using# 1 and 2 with consecutive 2 allowed  def CountWays(n):     # noOfWays[i] will store count for value i.    # 3 extra values are to take care of corner case n = 0    noOfWays = [0] * (n + 3)     noOfWays[0] = 1    noOfWays[1] = 1    noOfWays[2] = 1 + 1     # Loop till "n+1" to compute value for "n"    for i in range(3, n+1):        # number of ways if first run is 1        # +        # number of ways if first run is 2        # and second run is 1        noOfWays[i] = noOfWays[i-1] + noOfWays[i-3]    return noOfWays[n]  # Driver Codeif __name__ == '__main__':    n = 5    print(CountWays(n))
// Bottom up approach for// counting ways to reach a score using// 1 and 2 with consecutive 2 allowedusing System; class GfG{     static int CountWays(int n)    {        // if this state is already visited return        // its value        if (dp[n, flag] != -1)        {            return dp[n, flag];        }         // base case        if (n == 0)        {            return 1;        }         // 2 is not scored last time so we can        // score either 2 or 1        int sum = 0;        if (flag == 0 && n > 1)        {            sum = sum + CountWays(n - 1, 0) +                    CountWays(n - 2, 1);        }                 // 2 is scored last time so we can only score 1        else        {            sum = sum + CountWays(n - 1, 0);        }         return dp[n,flag] = sum;    }     // Driver code    public static void Main(String[] args)    {        int n = 5;        for (int i = 0; i <dp.GetLength(0); i++)            for (int j = 0; j < dp.GetLength(1); j++)                dp[i,j]=-1;    Console.WriteLine(CountWays(n, 0));    }} // This code has been contributed by 29AjayKumar
<script> // Bottom up approach for// counting ways to reach a score using// 1 and 2 with consecutive 2 allowed    function CountWays(n)    {             // noOfWays[i] will store count for value i.        // 3 extra values are to take care of cornser case n        // = 0        var noOfWays = Array(n + 3).fill(0);         noOfWays[0] = 1;        noOfWays[1] = 1;        noOfWays[2] = 1 + 1;         // Loop till "n+1" to compute value for "n"        for (var i = 3; i < n + 1; i++) {                 // number of ways if first run is 1        // number of ways if first run is 2        // and second run is 1            noOfWays[i] = noOfWays[i - 1] + noOfWays[i - 3];        }        return noOfWays[n];    }     // Driver code        var n = 5;        document.write(CountWays(n)); // This code is contributed by gauravrajput1</script>
6
 
This can be further improved to O(n) time and constant space by storing only last 3 values.
C++
Java
Python3
C#
Javascript
// Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed#include <iostream>using namespace std; int CountWays(int n){    // noOfWays[i] will store count    // for last 3 values before i.    int noOfWays[3];     noOfWays[0] = 1;    noOfWays[1] = 1;    noOfWays[2] = 1 + 1;         // Loop till "n+1" to compute value for "n"    for (int i=3; i<n+1; i++) {      noOfWays[i] =        // number of ways if first run is 1        noOfWays[3-1]        // number of ways if first run is 2        // and second run is 1        + noOfWays[3-3];             // Remember last 3 values      noOfWays[0] = noOfWays[1];      noOfWays[1] = noOfWays[2];      noOfWays[2] = noOfWays[i];    }    return noOfWays[n];} int main(){    int n = 5;    cout << CountWays(n);    return 0;}
// Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowedimport java.io.*;class GFG{ static int CountWays(int n){       // noOfWays[i] will store count    // for last 3 values before i.    int noOfWays[] = new int[n + 3];     noOfWays[0] = 1;    noOfWays[1] = 1;    noOfWays[2] = 1 + 1;         // Loop till "n+1" to compute value for "n"    for (int i=3; i<n+1; i++) {      noOfWays[i] =        // number of ways if first run is 1        noOfWays[3-1]        // number of ways if first run is 2        // and second run is 1        + noOfWays[3-3];             // Remember last 3 values      noOfWays[0] = noOfWays[1];      noOfWays[1] = noOfWays[2];      noOfWays[2] = noOfWays[i];    }    return noOfWays[n];}   // Driver codepublic static void main (String[] args) {    int n = 5;    System.out.println(CountWays(n));}} // This code is contributed by shivanisinghss2110
# Bottom up approach for# counting ways to reach a score using 1 and 2 with# consecutive 2 alloweddef CountWays(n):     # noOfWays[i] will store count    # for last 3 values before i.    noOfWays = [0] * (n+1)     noOfWays[0] = 1    noOfWays[1] = 1    noOfWays[2] = 1 + 1         # Loop till "n+1" to compute value for "n"    for i in range(3, n+1):                # number of ways if first run is 1        # number of ways if first run is 2        # and second run is 1        noOfWays[i] = noOfWays[3-1] + noOfWays[3-3]               # Remember last 3 values        noOfWays[0] = noOfWays[1]        noOfWays[1] = noOfWays[2]        noOfWays[2] = noOfWays[i]         return noOfWays[n]  if __name__ == '__main__':    n = 5    print(CountWays(n))     # this code is contributed by shivanisingh2110
// Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowedusing System;using System.Collections.Generic;public class GFG {     static int CountWays(int n) {         // noOfWays[i] will store count        // for last 3 values before i.        int []noOfWays = new int[n + 3];         noOfWays[0] = 1;        noOfWays[1] = 1;        noOfWays[2] = 1 + 1;         // Loop till "n+1" to compute value for "n"        for (int i = 3; i < n + 1; i++) {            noOfWays[i] =                    // number of ways if first run is 1                    noOfWays[3 - 1]                            // number of ways if first run is 2                            // and second run is 1                            + noOfWays[3 - 3];             // Remember last 3 values            noOfWays[0] = noOfWays[1];            noOfWays[1] = noOfWays[2];            noOfWays[2] = noOfWays[i];        }        return noOfWays[n];    }     // Driver code    public static void Main(String[] args) {        int n = 5;        Console.WriteLine(CountWays(n));    }} // This code is contributed by umadevi9616
<script>// Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowedfunction CountWays(n){     // noOfWays[i] will store count    // for last 3 values before i.    var noOfWays = Array(3).fill(0);     noOfWays[0] = 1;    noOfWays[1] = 1;    noOfWays[2] = 1 + 1;         // Loop till "n+1" to compute value for "n"    for (var i = 3; i < n + 1; i++) {      noOfWays[i] =        // number of ways if first run is 1        noOfWays[3-1]        // number of ways if first run is 2        // and second run is 1        + noOfWays[3-3];             // Remember last 3 values      noOfWays[0] = noOfWays[1];      noOfWays[1] = noOfWays[2];      noOfWays[2] = noOfWays[i];    }    return noOfWays[n];} var n = 5;document.write(CountWays(n)); // This code is contributed by shivanisinghss2110</script>
6
shrikanth13
Sach_Code
SURENDRA_GANGWAR
princiraj1992
29AjayKumar
surbhityagi15
SoumikMondal
puneetgarg80
GauravRajput1
shivanisinghss2110
umadevi9616
Oracle
Technical Scripter 2018
Dynamic Programming
Recursion
Oracle
Dynamic Programming
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Matrix Chain Multiplication | DP-8
Longest Palindromic Substring | Set 1
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction