简体   繁体   English

排列组合程序产生意外输出

[英]Program for permutation and combination yields an unexpected output

After thinking for quite a long time on how to make a Java program that outputs all the possible combinations from a given input array, I finally thought of doing so by combining recursion and iteration. 在考虑了很长的时间来思考如何制作一个从给定输入数组输出所有可能的组合的Java程序之后,我终于想到了将递归和迭代相结合的方法。

My code takes input a char array {a,b,c} and should give an output of all possible array of length 3. 我的代码接受一个char数组{a,b,c}的输入,并且应该给出长度为3的所有可能数组的输出。

My code is- 我的代码是-

public class Brute {

    char[] val = new char[] { 'a', 'b', 'c' };

    void work(char arr[], int i) {
        for (int j = 0; j <= 2; j++) {
            if (i <= 2) {
                arr[i] = val[j];
            }
            while (i <= 2) {
                i = i + 1;
                if (i <= 2) {
                    work(arr, i);
                    System.out.println(new String(arr));
                }
            }
        }
    }

    public static void main(String args[]) {
        Brute b = new Brute();
        char arr[] = new char[] { 'p', 'q', 'r' };
        b.work(arr, 0);

    }

}

The output is: 输出为:

aaa
aaa
aaa

I can't understand why it gives me this output instead of all combinations. 我不明白为什么它会给我这个输出而不是所有组合。

问题在于,不是将i的值重新初始化为0,而是始终将i的值保留为3,并且将i的递增值(即3)传递给其他递归调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM