我要生成一个字符串在C ++中的重复的所有变化,我会强烈preFER非递归算法。我拿出了复杂性递归算法在过去,但由于(R ^ N)我想看到一个迭代的方法。
I want to generate all variations with repetitions of a string in C++ and I'd highly prefer a non-recursive algorithm. I've come up with a recursive algorithm in the past but due to the complexity (r^n) I'd like to see an iterative approach.
我很惊讶,我没能找到解决这个问题的在网络上的任何位置或计算器。
I'm quite surprised that I wasn't able to find a solution to this problem anywhere on the web or on StackOverflow.
我已经想出了一个Python脚本,我想要做什么,以及:
I've come up with a Python script that does what I want as well:
import itertools
variations = itertools.product('ab', repeat=4)
for variations in variations:
variation_string = ""
for letter in variations:
variation_string += letter
print variation_string
输出:
AAAA AAAB AABA AABB ABAA ABAB ABBA AB | BB 咩咩咩 baab 巴巴 BABB BBAA bbab bbba BBBB
aaaa aaab aaba aabb abaa abab abba abbb baaa baab baba babb bbaa bbab bbba bbbb
在理想情况下,我想一个C ++程序,可以产生精确的输出,以完全相同的参数。
Ideally I'd like a C++ program that can produce the exact output, taking the exact same parameters.
这是用于学习目的,它不是功课。我希望我的家庭作业,是这样的。
This is for learning purposes, it isn't homework. I wish my homework was like that.
推荐答案
您可以把它作为计数,在基数等于字符的字母数字(以特殊照顾的多个相同字符的字母如果是这样的一个可能的输入)。该 AAAA AAAB AABA ...
例如举例来说,实际上是数字的二进制再presentation 0-15。
You could think of it as counting, in a radix equal to the number of characters in the alphabet (taking special care of multiple equal characters in the alphabet if that's a possible input). The aaaa aaab aaba ...
example for instance, is actually the binary representation of the numbers 0-15.
刚做基数转换搜索,落实相应的角色,从每一个数字的映射,然后简单地做一个for循环,从0到word_length alphabet_size
Just do a search on radix transformations, implement a mapping from each "digit" to corresponding character, and then simply do a for loop from 0 to word_lengthalphabet_size
这种算法应当在需要使用的存储器恒定量的产生时间成线性比例字符串数运行。
Such algorithm should run in time linearly proportional to the number of strings that needs to be produced using constant amount of memory.
示范使用Java
public class Test {
public static void main(String... args) {
// Limit imposed by Integer.toString(int i, int radix) which is used
// for the purpose of this demo.
final String chars = "0123456789abcdefghijklmnopqrstuvwxyz";
int wordLength = 3;
char[] alphabet = { 'a', 'b', 'c' };
for (int i = 0; i < Math.pow(wordLength, alphabet.length); i++) {
String str = Integer.toString(i, alphabet.length);
String result = "";
while (result.length() + str.length() < wordLength)
result += alphabet[0];
for (char c : str.toCharArray())
result += alphabet[chars.indexOf(c)];
System.out.println(result);
}
}
}
输出:
aaa
aab
aac
aba
abb
abc
aca
acb
acc
baa
bab
bac
bba
bbb
bbc
bca
bcb
bcc
caa
cab
cac
cba
cbb
cbc
cca
ccb
ccc
相关推荐
最新文章