Sup*_*sor 5 java arrays combinations character
我有一个字符数组c [] [],每个索引都有不同的映射.例如:
{'a', 'b', 'c', 'd', 'e', 'f' } {'g', 'h', 'i' }
Run Code Online (Sandbox Code Playgroud)
我需要将此数组的所有可能字符组合作为字符串返回.这意味着,对于上面的字符数组,我应该返回:"ag","ah","ai","bg","bh","bi","cg","ch","ci"等对于只有两个像上面这样的东西的字符数组来说很容易做到这一点,但是如果有更多的数组,那么我不知道该做什么......我要求大家帮助我!:)
das*_*ght 10
对于两个数组,两个嵌套循环应该:
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
要获得更多嵌套,您需要一个递归或等效的基于堆栈的解决方案.
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
从main()
这样的调用这个递归函数:
combos(0, c, "");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3608 次 |
最近记录: |