获取数组中所有可能的字符组合

时间:2022-08-09 21:39:29

I have an array of characters c[][] with different mappings to each index. For example:

我有一个字符数组c [] [],每个索引都有不同的映射。例如:

{'a', 'b', 'c', 'd', 'e', 'f' } {'g', 'h', 'i' }

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! :)

我需要将此数组的所有可能字符组合作为字符串返回。这意味着,对于上面的字符数组,我应该返回:“ag”,“ah”,“ai”,“bg”,“bh”,“bi”,“cg”,“ch”,“ci”等对于只有两个像上面这样的东西的字符数组来说很容易做到这一点,但是如果有更多的数组,那么我不知道该做什么......我要求大家帮助我! :)

1 个解决方案

#1


10  

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]);
    }
}

Call this recursive function from your main() like this:

从main()调用此递归函数,如下所示:

combos(0, c, "");

#1


10  

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]);
    }
}

Call this recursive function from your main() like this:

从main()调用此递归函数,如下所示:

combos(0, c, "");