📌  相关文章
📜  在给定约束下使用 a、b 和 c 可以形成的字符串计数

📅  最后修改于: 2021-09-17 07:16:13             🧑  作者: Mango

给定长度 n,计算可以使用 ‘a’、’b’ 和 ‘c’ 生成的长度为 n 的字符串的数量,最多允许一个 ‘b’ 和两个 ‘c’。
例子 :

Input : n = 3 
Output : 19 
Below strings follow given constraints:
aaa aab aac aba abc aca acb acc baa
bac bca bcc caa cab cac cba cbc cca ccb 

Input  : n = 4
Output : 39

在谷歌面试中被问到

一个简单的解决方案是递归计算所有可能的字符串组合,直到后面的“a”、“b”和“c”。
以下是上述想法的实现

C++
// C++ program to count number of strings
// of n characters with
#include
using namespace std;
 
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
int countStr(int n, int bCount, int cCount)
{
    // Base cases
    if (bCount < 0 || cCount < 0) return 0;
    if (n == 0) return 1;
    if (bCount == 0 && cCount == 0) return 1;
 
    // Three cases, we choose, a or b or c
    // In all three cases n decreases by 1.
    int res = countStr(n-1, bCount, cCount);
    res += countStr(n-1, bCount-1, cCount);
    res += countStr(n-1, bCount, cCount-1);
 
    return res;
}
 
// Driver code
int main()
{
    int n = 3;  // Total number of characters
    cout << countStr(n, 1, 2);
    return 0;
}


Java
// Java program to count number
// of strings of n characters with
import java.io.*;
 
class GFG
{
     
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
static int countStr(int n,
                    int bCount,
                    int cCount)
{
    // Base cases
    if (bCount < 0 || cCount < 0) return 0;
    if (n == 0) return 1;
    if (bCount == 0 && cCount == 0) return 1;
 
    // Three cases, we choose, a or b or c
    // In all three cases n decreases by 1.
    int res = countStr(n - 1, bCount, cCount);
    res += countStr(n - 1, bCount - 1, cCount);
    res += countStr(n - 1, bCount, cCount - 1);
 
    return res;
}
 
// Driver code
public static void main (String[] args)
{
    int n = 3; // Total number of characters
    System.out.println(countStr(n, 1, 2));
}
}
 
// This code is contributed by akt_mit


Python 3
# Python 3 program to
# count number of strings
# of n characters with
 
# n is total number of characters.
# bCount and cCount are counts
# of 'b' and 'c' respectively.
def countStr(n, bCount, cCount):
 
    # Base cases
    if (bCount < 0 or cCount < 0):
        return 0
    if (n == 0) :
        return 1
    if (bCount == 0 and cCount == 0):
        return 1
 
    # Three cases, we choose, a or b or c
    # In all three cases n decreases by 1.
    res = countStr(n - 1, bCount, cCount)
    res += countStr(n - 1, bCount - 1, cCount)
    res += countStr(n - 1, bCount, cCount - 1)
 
    return res
 
# Driver code
if __name__ =="__main__":
    n = 3 # Total number of characters
    print(countStr(n, 1, 2))
 
# This code is contributed
# by ChitraNayal


C#
// C# program to count number
// of strings of n characters
// with a, b and c under given
// constraints
using System;
 
class GFG
{
     
// n is total number of
// characters. bCount and
// cCount are counts of
// 'b' and 'c' respectively.
static int countStr(int n,
                    int bCount,
                    int cCount)
{
    // Base cases
    if (bCount < 0 || cCount < 0)
        return 0;
    if (n == 0) return 1;
    if (bCount == 0 && cCount == 0)
        return 1;
 
    // Three cases, we choose,
    // a or b or c. In all three
    // cases n decreases by 1.
    int res = countStr(n - 1,
                       bCount, cCount);
    res += countStr(n - 1,
                    bCount - 1, cCount);
    res += countStr(n - 1,
                    bCount, cCount - 1);
 
    return res;
}
 
// Driver code
static public void Main ()
{
    // Total number
    // of characters
    int n = 3;
    Console.WriteLine(countStr(n, 1, 2));
}
}
 
// This code is contributed by aj_36


PHP


Javascript


C++
// C++ program to count number of strings
// of n characters with
#include
using namespace std;
 
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
int countStrUtil(int dp[][2][3], int n, int bCount=1,
                 int cCount=2)
{
    // Base cases
    if (bCount < 0 || cCount < 0) return 0;
    if (n == 0) return 1;
    if (bCount == 0 && cCount == 0) return 1;
 
    // if we had saw this combination previously
    if (dp[n][bCount][cCount] != -1)
        return dp[n][bCount][cCount];
 
    // Three cases, we choose, a or b or c
    // In all three cases n decreases by 1.
    int res = countStrUtil(dp, n-1, bCount, cCount);
    res += countStrUtil(dp, n-1, bCount-1, cCount);
    res += countStrUtil(dp, n-1, bCount, cCount-1);
 
    return (dp[n][bCount][cCount] = res);
}
 
// A wrapper over countStrUtil()
int countStr(int n)
{
    int dp[n+1][2][3];
    memset(dp, -1, sizeof(dp));
    return countStrUtil(dp, n);
}
 
// Driver code
int main()
{
    int n = 3; // Total number of characters
    cout << countStr(n);
    return 0;
}


Java
// Java program to count number of strings
// of n characters with
 
class GFG
{
    // n is total number of characters.
    // bCount and cCount are counts of 'b'
    // and 'c' respectively.
 
    static int countStrUtil(int[][][] dp, int n,
                            int bCount, int cCount)
    {
 
        // Base cases
        if (bCount < 0 || cCount < 0)
        {
            return 0;
        }
        if (n == 0)
        {
            return 1;
        }
        if (bCount == 0 && cCount == 0)
        {
            return 1;
        }
 
        // if we had saw this combination previously
        if (dp[n][bCount][cCount] != -1)
        {
            return dp[n][bCount][cCount];
        }
 
        // Three cases, we choose, a or b or c
        // In all three cases n decreases by 1.
        int res = countStrUtil(dp, n - 1, bCount, cCount);
        res += countStrUtil(dp, n - 1, bCount - 1, cCount);
        res += countStrUtil(dp, n - 1, bCount, cCount - 1);
 
        return (dp[n][bCount][cCount] = res);
    }
 
    // A wrapper over countStrUtil()
    static int countStr(int n, int bCount, int cCount)
    {
        int[][][] dp = new int[n + 1][2][3];
        for (int i = 0; i < n + 1; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                for (int k = 0; k < 3; k++)
                {
                    dp[i][j][k] = -1;
                }
            }
        }
        return countStrUtil(dp, n,bCount,cCount);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 3; // Total number of characters
        int bCount = 1, cCount = 2;
        System.out.println(countStr(n,bCount,cCount));
    }
}
 
// This code has been contributed by 29AjayKumar


Python3
# Python 3 program to count number of strings
# of n characters with
 
# n is total number of characters.
# bCount and cCount are counts of 'b'
# and 'c' respectively.
def countStrUtil(dp, n, bCount=1,cCount=2):
 
    # Base cases
    if (bCount < 0 or cCount < 0):
        return 0
    if (n == 0):
        return 1
    if (bCount == 0 and cCount == 0):
        return 1
 
    # if we had saw this combination previously
    if (dp[n][bCount][cCount] != -1):
        return dp[n][bCount][cCount]
 
    # Three cases, we choose, a or b or c
    # In all three cases n decreases by 1.
    res = countStrUtil(dp, n-1, bCount, cCount)
    res += countStrUtil(dp, n-1, bCount-1, cCount)
    res += countStrUtil(dp, n-1, bCount, cCount-1)
 
    dp[n][bCount][cCount] = res
    return dp[n][bCount][cCount]
 
# A wrapper over countStrUtil()
def countStr(n):
 
    dp = [ [ [-1 for x in range(n+2)] for y in range(3)]for z in range(4)]
    return countStrUtil(dp, n)
 
# Driver code
if __name__ == "__main__":
     
    n = 3 # Total number of characters
    print(countStr(n))
     
# This code is contributed by chitranayal


C#
// C# program to count number of strings
// of n characters with
using System;
 
class GFG
{
    // n is total number of characters.
    // bCount and cCount are counts of 'b'
    // and 'c' respectively.
    static int countStrUtil(int[,,] dp, int n,
                    int bCount=1, int cCount=2)
    {
        // Base cases
        if (bCount < 0 || cCount < 0)
            return 0;
        if (n == 0)
            return 1;
        if (bCount == 0 && cCount == 0)
            return 1;
     
        // if we had saw this combination previously
        if (dp[n,bCount,cCount] != -1)
            return dp[n,bCount,cCount];
     
        // Three cases, we choose, a or b or c
        // In all three cases n decreases by 1.
        int res = countStrUtil(dp, n - 1, bCount, cCount);
        res += countStrUtil(dp, n - 1, bCount - 1, cCount);
        res += countStrUtil(dp, n - 1, bCount, cCount - 1);
     
        return (dp[n, bCount, cCount] = res);
    }
     
    // A wrapper over countStrUtil()
    static int countStr(int n)
    {
        int[,,] dp = new int[n + 1, 2, 3];
        for(int i = 0; i < n + 1; i++)
            for(int j = 0; j < 2; j++)
                for(int k = 0; k < 3; k++)
                    dp[i, j, k] = -1;
        return countStrUtil(dp, n);
    }
     
    // Driver code
    static void Main()
    {
        int n = 3; // Total number of characters
         
        Console.Write(countStr(n));
    }
}
 
// This code is contributed by DrRoot_


Javascript


C++
// A O(1) CPP program to find number of strings
// that can be made under given constraints.
#include
using namespace std;
int countStr(int n){
     
    int count = 0;
     
    if(n>=1){
        //aaa...
        count += 1;
        //b...aaa...
          count += n;
        //c...aaa...
        count += n;
         
        if(n>=2){
          //bc...aaa...
          count += n*(n-1);
          //cc...aaa...
          count += n*(n-1)/2;
           
          if(n>=3){
            //bcc...aaa...
            count += (n-2)*(n-1)*n/2;
          }
        }
     
    }
     
    return count;
     
}
 
// Driver code
int main()
{
  int n = 3;
  cout << countStr(n);
  return 0;
}


Java
// A O(1) Java program to
// find number of strings
// that can be made under
// given constraints.
import java.io.*;
 
class GFG
{
    static int countStr(int n)
    {
    return 1 + (n * 2) +
           (n * ((n * n) - 1) / 2);
    }
 
// Driver code
public static void main (String[] args)
{
    int n = 3;
    System.out.println( countStr(n));
}
}
 
// This code is contributed by ajit


Python 3
# A O(1) Python3 program to find
# number of strings that can be
# made under given constraints.
 
def countStr(n):
    return (1 + (n * 2) +
                (n * ((n * n) - 1) // 2))
 
# Driver code
if __name__ == "__main__":
    n = 3
    print(countStr(n))
 
# This code is contributed
# by ChitraNayal


C#
// A O(1) C# program to
// find number of strings
// that can be made under
// given constraints.
using System;
 
class GFG
{
    static int countStr(int n)
    {
    return 1 + (n * 2) +
          (n * ((n * n) - 1) / 2);
    }
 
// Driver code
static public void Main ()
{
    int n = 3;
    Console.WriteLine(countStr(n));
}
}
 
// This code is contributed by m_kit


PHP


Javascript


输出 :

19

上述解决方案的时间复杂度是指数级的。高效的解决方案
如果我们淹没上述代码的递归树,我们会注意到相同的值出现了多次。所以我们存储结果,如果重复的话,以后会用到。

C++

// C++ program to count number of strings
// of n characters with
#include
using namespace std;
 
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
int countStrUtil(int dp[][2][3], int n, int bCount=1,
                 int cCount=2)
{
    // Base cases
    if (bCount < 0 || cCount < 0) return 0;
    if (n == 0) return 1;
    if (bCount == 0 && cCount == 0) return 1;
 
    // if we had saw this combination previously
    if (dp[n][bCount][cCount] != -1)
        return dp[n][bCount][cCount];
 
    // Three cases, we choose, a or b or c
    // In all three cases n decreases by 1.
    int res = countStrUtil(dp, n-1, bCount, cCount);
    res += countStrUtil(dp, n-1, bCount-1, cCount);
    res += countStrUtil(dp, n-1, bCount, cCount-1);
 
    return (dp[n][bCount][cCount] = res);
}
 
// A wrapper over countStrUtil()
int countStr(int n)
{
    int dp[n+1][2][3];
    memset(dp, -1, sizeof(dp));
    return countStrUtil(dp, n);
}
 
// Driver code
int main()
{
    int n = 3; // Total number of characters
    cout << countStr(n);
    return 0;
}

Java

// Java program to count number of strings
// of n characters with
 
class GFG
{
    // n is total number of characters.
    // bCount and cCount are counts of 'b'
    // and 'c' respectively.
 
    static int countStrUtil(int[][][] dp, int n,
                            int bCount, int cCount)
    {
 
        // Base cases
        if (bCount < 0 || cCount < 0)
        {
            return 0;
        }
        if (n == 0)
        {
            return 1;
        }
        if (bCount == 0 && cCount == 0)
        {
            return 1;
        }
 
        // if we had saw this combination previously
        if (dp[n][bCount][cCount] != -1)
        {
            return dp[n][bCount][cCount];
        }
 
        // Three cases, we choose, a or b or c
        // In all three cases n decreases by 1.
        int res = countStrUtil(dp, n - 1, bCount, cCount);
        res += countStrUtil(dp, n - 1, bCount - 1, cCount);
        res += countStrUtil(dp, n - 1, bCount, cCount - 1);
 
        return (dp[n][bCount][cCount] = res);
    }
 
    // A wrapper over countStrUtil()
    static int countStr(int n, int bCount, int cCount)
    {
        int[][][] dp = new int[n + 1][2][3];
        for (int i = 0; i < n + 1; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                for (int k = 0; k < 3; k++)
                {
                    dp[i][j][k] = -1;
                }
            }
        }
        return countStrUtil(dp, n,bCount,cCount);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 3; // Total number of characters
        int bCount = 1, cCount = 2;
        System.out.println(countStr(n,bCount,cCount));
    }
}
 
// This code has been contributed by 29AjayKumar

蟒蛇3

# Python 3 program to count number of strings
# of n characters with
 
# n is total number of characters.
# bCount and cCount are counts of 'b'
# and 'c' respectively.
def countStrUtil(dp, n, bCount=1,cCount=2):
 
    # Base cases
    if (bCount < 0 or cCount < 0):
        return 0
    if (n == 0):
        return 1
    if (bCount == 0 and cCount == 0):
        return 1
 
    # if we had saw this combination previously
    if (dp[n][bCount][cCount] != -1):
        return dp[n][bCount][cCount]
 
    # Three cases, we choose, a or b or c
    # In all three cases n decreases by 1.
    res = countStrUtil(dp, n-1, bCount, cCount)
    res += countStrUtil(dp, n-1, bCount-1, cCount)
    res += countStrUtil(dp, n-1, bCount, cCount-1)
 
    dp[n][bCount][cCount] = res
    return dp[n][bCount][cCount]
 
# A wrapper over countStrUtil()
def countStr(n):
 
    dp = [ [ [-1 for x in range(n+2)] for y in range(3)]for z in range(4)]
    return countStrUtil(dp, n)
 
# Driver code
if __name__ == "__main__":
     
    n = 3 # Total number of characters
    print(countStr(n))
     
# This code is contributed by chitranayal   

C#

// C# program to count number of strings
// of n characters with
using System;
 
class GFG
{
    // n is total number of characters.
    // bCount and cCount are counts of 'b'
    // and 'c' respectively.
    static int countStrUtil(int[,,] dp, int n,
                    int bCount=1, int cCount=2)
    {
        // Base cases
        if (bCount < 0 || cCount < 0)
            return 0;
        if (n == 0)
            return 1;
        if (bCount == 0 && cCount == 0)
            return 1;
     
        // if we had saw this combination previously
        if (dp[n,bCount,cCount] != -1)
            return dp[n,bCount,cCount];
     
        // Three cases, we choose, a or b or c
        // In all three cases n decreases by 1.
        int res = countStrUtil(dp, n - 1, bCount, cCount);
        res += countStrUtil(dp, n - 1, bCount - 1, cCount);
        res += countStrUtil(dp, n - 1, bCount, cCount - 1);
     
        return (dp[n, bCount, cCount] = res);
    }
     
    // A wrapper over countStrUtil()
    static int countStr(int n)
    {
        int[,,] dp = new int[n + 1, 2, 3];
        for(int i = 0; i < n + 1; i++)
            for(int j = 0; j < 2; j++)
                for(int k = 0; k < 3; k++)
                    dp[i, j, k] = -1;
        return countStrUtil(dp, n);
    }
     
    // Driver code
    static void Main()
    {
        int n = 3; // Total number of characters
         
        Console.Write(countStr(n));
    }
}
 
// This code is contributed by DrRoot_

Javascript


输出 :

19

时间复杂度: O(n)
辅助空间: O(n)
感谢懒惰先生提出上述解决方案。
在 O(1) 时间内工作的解决方案:

我们可以应用组合学的概念在恒定时间内解决这个问题。我们可以回忆一下公式,我们总共可以排列n个对象的方式数,其中p个对象是一种类型,q个对象是另一种类型,r个对象是第三种类型!/( p!q!r!)

让我们一步一步地走向解决方案。

我们可以在没有 ‘b’ 和 ‘c’ 的情况下形成多少个字符串?答案是1,因为我们可以安排一个字符串仅由“A”只能用一种方法和字符串将是AAAA …。(n次)。

我们可以用一个 ‘b’ 形成多少个字符串?答案是 n,因为我们可以排列一个由 (n-1) 个 ‘a’s 和 1 个 ‘b’ 组成的字符串!/(n-1)! = n。 ‘c’ 也是如此。

我们可以用 2 个位置组成多少个字符串,用 ‘b’ 和/或 ‘c’ 填充?答案是 n*(n-1) + n*(n-1)/2 。因为,根据我们给定的约束,那 2 个位置可以是 1 ‘b’ 和 1 ‘c’ 或 2 ‘c’。对于第一种情况,排列总数为 n!/(n-2)! = n*(n-1) 第二种情况是 n!/(2!(n-2)!) = n*(n-1)/2 。

最后,我们可以用 3 个位置组成多少个字符串,用 ‘b’ 和/或 ‘c’ 填充?答案是 (n-2)*(n-1)*n/2 。因为,根据我们给定的约束,那 3 个位置只能由 1 个 ‘b’ 和 2’c’ 组成。所以,排列的总数是 n!/(2!(n-3)!) = (n-2)*(n-1)*n/2 。

C++

// A O(1) CPP program to find number of strings
// that can be made under given constraints.
#include
using namespace std;
int countStr(int n){
     
    int count = 0;
     
    if(n>=1){
        //aaa...
        count += 1;
        //b...aaa...
          count += n;
        //c...aaa...
        count += n;
         
        if(n>=2){
          //bc...aaa...
          count += n*(n-1);
          //cc...aaa...
          count += n*(n-1)/2;
           
          if(n>=3){
            //bcc...aaa...
            count += (n-2)*(n-1)*n/2;
          }
        }
     
    }
     
    return count;
     
}
 
// Driver code
int main()
{
  int n = 3;
  cout << countStr(n);
  return 0;
}

Java

// A O(1) Java program to
// find number of strings
// that can be made under
// given constraints.
import java.io.*;
 
class GFG
{
    static int countStr(int n)
    {
    return 1 + (n * 2) +
           (n * ((n * n) - 1) / 2);
    }
 
// Driver code
public static void main (String[] args)
{
    int n = 3;
    System.out.println( countStr(n));
}
}
 
// This code is contributed by ajit

Python3

# A O(1) Python3 program to find
# number of strings that can be
# made under given constraints.
 
def countStr(n):
    return (1 + (n * 2) +
                (n * ((n * n) - 1) // 2))
 
# Driver code
if __name__ == "__main__":
    n = 3
    print(countStr(n))
 
# This code is contributed
# by ChitraNayal

C#

// A O(1) C# program to
// find number of strings
// that can be made under
// given constraints.
using System;
 
class GFG
{
    static int countStr(int n)
    {
    return 1 + (n * 2) +
          (n * ((n * n) - 1) / 2);
    }
 
// Driver code
static public void Main ()
{
    int n = 3;
    Console.WriteLine(countStr(n));
}
}
 
// This code is contributed by m_kit

PHP


Javascript


输出 :

19

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程