从此递归解决方案中删除 static int 计数器

Remove static int counter from this recursive solution

我有这个递归代码来计算一个字符串可以有的排列数

public class Permutation {

static int counter = 0;

public static int perms(String s, int level,int length) {

    if(level == length-1) {
        counter++;
    }
    else {
        for (int i = 0; i < s.length(); i++) {
            String newString = s.substring(0, i) + s.substring(i + 1);
            perms(newString,level + 1, length);
        }
    }
    return counter;

}

public static void main(String[] args) {

    System.out.println(perms("plot", 0, 4));

}

}

我想知道如何重写它以便它不使用 static int counter = 0?谢谢!

注意:是的,我知道我可以为此使用置换公式哈哈

您可以将计数器作为第四个参数传递(使用 0 作为初始值)。 Return 它来自 perms 并将其设置为从内部调用返回的值。

public static int perms2(String s, int level,int length, int count){
        if(level == length-1){
            count++;
        }
        else {
            for (int i = 0; i < s.length(); i++) {
                String newString = s.substring(0,i)+s.substring(i+1);
                count = perms2(newString,level+1,length, count);
            }
        }
        return count;
    }

无需静态计数器或将计数器值传递给每个方法调用。请注意,您的实现计算所有排列而不是唯一排列(字符串“aab”returns 6,而不是 3)。


public static int permsRedone(String s, int level,int length){
  int count = 0;

  if(level == length-1){
    return 1;
  }
  else {
    for (int i = 0; i < s.length(); i++) {
      String newString = s.substring(0,i)+s.substring(i+1);
      count += permsRedone(newString,level+1,length);
    }
  }
  return count;

}