获得的字符的所有可能组合以阵列 [英] Get all possible combinations of characters in an array
问题描述
我有字符C [] []具有不同映射的每个索引的阵列。
例如:
I have an array of characters c[][] with different mappings to each index. For example:
{'a', 'b', 'c', 'd', 'e', 'f' } {'g', 'h', 'i' }
我需要返回所有可能的字符组合为这个数组作为字符串。
那意思,对于上面的字符数组,我应该返回:
股份公司,啊,人工智能,BG,BH,比,CG,CH,CI等。
这将是很容易的只有两个像上面的东西字符数组做到这一点,但如果有多个阵列,那么我不知道该怎么办......
这就是我要求你们帮我! :)
I need to return all the possible character combinations for this array as a string. That meaning, for the above character array, I should return: "ag", "ah", "ai", "bg", "bh", "bi", "cg", "ch", "ci", etc. It would be easy to do this for a character array of only two things like above, but if there are more arrays, then I do not know what to do... Which is what I am asking you all to help me with! :)
推荐答案
有关两个数组的嵌套循环应该做的:
For two arrays two nested loops should do:
for (int i = 0 ; i != c[0].length ; i++) {
for (int j = 0 ; j != c[1].length ; j++) {
System.out.writeln(""+c[0][i]+c[1][j]);
}
}
有关更多的嵌套,你需要一个递归或等效的基于堆栈的解决方案。
For more nesting you would need a recursive or an equivalent stack-based solution.
void combos(int pos, char[][] c, String soFar) {
if (pos == c.length) {
System.out.writeln(soFar);
return;
}
for (int i = 0 ; i != c[pos].length ; i++) {
combos(pos+1, c, soFar + c[pos][i]);
}
}
从调用该递归函数的的main()
是这样的:
combos(0, c, "");
这篇关于获得的字符的所有可能组合以阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!