使用 C++ 中的给定组合计算字符串(由 R、G 和 B 组成)的数量
仅给定三个数字R、G和B以及字母“R”、“G”和“B”。目标是找到可以使用其中至少RRs、至少GGs和至少BBs组成的可能字符串的数量。数字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(intR,intG,intB,intsize)接受所有输入并使用给定组合返回字符串(由R、G和B组成)的计数。
取初始计数为0。
将剩余计数作为temp=size−(R+G+B)。
取一个长度为size+1的数组arr来取排列的值。
最初将i的阶乘存储在arr[i]中。使用从i=0到i=size的for循环。设置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循环结束时,我们将计算所需的字符串数量。
返回计数作为结果。
示例
#includeusing 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: "< 输出结果 如果我们运行上面的代码,它将生成以下输出-
Count of number of strings (made of R, G and B) using given combination are: 12