Get all possible combinations of characters in an array

前端 未结 1 1352
故里飘歌
故里飘歌 2020-12-18 03:56

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

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


        
相关标签:
1条回答
  • 2020-12-18 04:40

    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:

    combos(0, c, "");
    
    0 讨论(0)
提交回复
热议问题