给定一个数字 0-9 和一个整数 n 的数组,找到可以从输入数组中形成的所有整数,位数 = n



请注意,这不是这个的重复,而是它的子问题。

问题是这样的:

您将获得一个由数字 0-9 和一个整数 n 组成的数组。该数组可能包含任何给定数字的副本。找到所有可以通过污染输入数组中的数字并具有 n 位数字形成的整数。输入数组中的数字可以在输出的元素中重复。

例如,给定为输入 [2, 5] 和 n = 3,则输出应为以下内容:

[222, 225,252, 255, 522, 525, 552, 555]

请注意,这是 Python 的 itertools.product 计算的结果。他们的算法列在该链接中 - 虽然我无法确定其运行时复杂性,但我猜它是最佳的。该解决方案的运行时复杂度是多少?

vector<string> result;
// storing the concatenation of digits as a string as it is to operate on, we can convert the concatenated string to int at the end.
FormDigits(vector<int> input, int index, int n, string ndigits) {
// if the ndigits size has reached n
// Check whether that is already present in the result as we have repeating digits
if(ndigits.size() == n && result.find(ndigits) != result.end()) { 
result.push(ndigits);
} 
// if ndigits size hasnt yet reached run a loop and add next digit 
else {
for(int i=index; i<input.size(); i++) {
FormDigits(input,i,n,digit+to_string(arr[i]));
}
}
}

上述函数应从 main 调用为

FormDigits(InputArray, 0, n, "");

结果向量是最终输出。

最新更新