有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java程序中的冗余组合

我想打印每一个可能的组合,使用给定的字母而不改变字母顺序,所以我写了这个代码,但它会一次又一次地打印每一行,问题是什么

public class Solutions {


    public static void main(String[] args) {
        //  Scanner scanner = new Scanner(System.in);

        c = "l u k".split(" ");
        Solutions solutions = new Solutions();
        solutions.combi(0);
        System.out.println("Number of combi = " + count);

        System.out.print(max);
    }

    static String[] c;
    static int count = 0;
    static int max = 0;


    public void combi(int start) {

        int j;
        if (start != 0) {
            String str = "";
            for (int i = 0; i < start; i++) {
               // System.out.print(c[i]);
                str += c[i];
            }


          //  System.out.println();
            count++;
        }

        for (j = start; j < c.length; j++) {


            combi(start + 1);


        }

    }

}

共 (1) 个答案

  1. # 1 楼答案

    public void combi(int start) {
        int j;
        if (start != 0) {
            for (int i = 0; i < start; i++) {
                System.out.print(c[i]);
            }
    
            System.out.println();
            count++;
        } else {
            for (j = start+1; j <= c.length; j++) {
                combi(j);
            }
        }
    }