简体   繁体   English

为什么我不能从我的递归方法中得到任何输出?

[英]Why can't I get any output from my recursive method?

I'm trying to insert the characters (a, b, c) and get the permutation of the array.我正在尝试插入字符 (a, b, c) 并获取数组的排列。

For some reason its not printing out.由于某种原因,它没有打印出来。 I'm sure its a simple mistake but I can't find it.我确定这是一个简单的错误,但我找不到它。 Much appreciative for the advice.非常感谢您的建议。

public static void main(String[] args) {

    int [] A = new int []{'a','b','c'};
    permute(A, 3);
}

public static void permute(int[] A, int p){
    if(A.length == 0){
        return;
    }
    for(int i = 0; i < A.length; i++){
        char ch = (char) p;
        p += A[i];
        permute(A,p);
        p = ch;
    }
}

There are several problems with your approach:你的方法有几个问题:

  • You use char s when you should use int s and vice versa;应该使用int时使用char ,反之亦然;
  • The program doesn't contain any System.out.print statements, so you never instruct the Java program to print anything;该程序不包含任何System.out.print语句,因此您永远不会指示 Java 程序打印任何内容;
  • This isn't a program that enumerates over all possible permutations.这不是一个枚举所有可能排列的程序。 This will in fact generate a stack overflow exception (not to be confused with the name of this site), simply because the length of the array never changes, thus you always will call the for part and keep building up a call stack;这实际上会产生堆栈溢出异常(不要与本站点的名称混淆),仅仅是因为数组的长度永远不会改变,因此您总是会调用for部分并不断构建调用堆栈; and
  • It is unclear what p means.不清楚p是什么意思。

An in-line permutation program looks like:直列排列的程序是这样的:

public static void permute(char[] a, int p){
    if(p >= a.length) {//we've reached the end of the array, now print
        for(int i = 0; i < a.length; i++) {
            System.out.print(a[i]);
        }
        System.out.println();
    } else {
        char cp = a[p];
        for(int i = p; i < a.length; i++){
            char ci = a[i];
            a[p] = ci;
            a[i] = cp;
            permute(a,p+1);
            a[i] = ci;
        }
        a[p] = cp;
    }
}

online jDoodle .在线 jDoodle

Then you call the method with permute(a,0) with a the list of characters you wish to permutate.然后调用该方法permute(a,0)a你想排列替换字符的列表。

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

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