仅给定三个数字 R、G 和 B 以及字母“R”、“G”和“B”。目标是找到可以使用其中至少 R Rs、至少 G Gs 和至少 B Bs 组成的可能字符串的数量。数字 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] 中。使用从 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 循环结束时,我们将计算所需的字符串数量。
返回计数作为结果。
#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