使用給定組合在C++中計算字串(由R、G和B組成)的數量


給定三個數字R、G和B,以及只有字母‘R’、‘G’和‘B’。目標是找到可以使用至少R個R、至少G個G和至少B個B組成的字串的數量。R、G和B的總和小於或等於可能的字串長度。

例如

輸入

R = 1, G = 1, B = 1 length=3

輸出

Count of number of strings (made of R, G and B) using given combination are −
6

解釋

The possible strings will be :
“RGB”, “RBG”, “BRG”, “BGR”, “GRB”, “GBR”. That is permutations of RGB.

輸入

R = 2, G = 0, B = 2 length=4

輸出

Count of number of strings (made of R, G and B) using given combination are −
6

解釋

The possible strings will be :
“RRBB”, “BBRR”, “RBRB”, “BRBR”, “RBBR”, “BRRB”.

以下程式中使用的方案如下

在這個方案中,我們首先取R、B和G字母的次數。現在檢查剩餘長度-(R+G+B)字母,進行所有排列組合並新增到計數中。

  • 以整數R、G、B作為輸入。

  • 將大小作為要生成的字串的長度。

  • 函式combination(int R, int G, int B, int size)接受所有輸入並返回使用給定組合的字串(由R、G和B組成)的數量。

  • 將初始計數設定為0。

  • 將剩餘計數設定為temp=size − (R + G + B)。

  • 建立一個長度為size+1的陣列arr來儲存排列的值。

  • 最初將i的階乘儲存在arr[i]中。使用for迴圈,從i=0到i=size。設定arr[i]=arr[i−1]*i。

  • 為了計算組合,使用兩個for迴圈再次遍歷arr[]。

  • 對於i=0到temp和j=0到temp−i,計算temp_2 = temp − (i + j)。

  • 取temp_3 = arr[i + R] * arr[j + B] * arr[temp_2 + G]。

  • 現在將arr[size] / temp_3新增到計數中。

  • 在所有for迴圈結束時,我們將count作為所需的可能的字串數量。

  • 返回count作為結果。

示例

 線上演示

#include<bits/stdc++.h>
using namespace std;
int combination(int R, int G, int B, int size){
   int count = 0;
   int temp = size − (R + G + B);
   int arr[size+1];
   arr[0] = 1;
   for (int i = 1; i <= size; i++){
      arr[i] = arr[i − 1] * i;
   }
   for (int i = 0; i <= temp; i++){
      for (int j = 0; j <= temp−i; j++){
         int temp_2 = temp − (i + j);
         int temp_3 = arr[i + R] * arr[j + B] * arr[temp_2 + G];
         count += arr[size] / temp_3;
      }
   }
   return count;
}
int main(){
   int R = 2, G = 1, B = 1;
   int size = 4;
   cout<<"Count of number of strings (made of R, G and B) using given combination are:
   "<<combination(R, G, B, size);
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Count of number of strings (made of R, G and B) using given combination are: 12

更新於:2021年1月5日

309 次瀏覽

開啟您的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.