使用给定组合在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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP