英文:
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
?谢谢!
注意:是的,我知道我可以使用排列公式来计算这个哈哈。
英文:
I have this recursive code for counting the number of permutations a string can have
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));
}
}
I was wondering how I can rewrite it so that it doesn't use static int counter = 0
? Thanks!
NOTE: Yes, I know I can just use the permutation formula for this haha
答案1
得分: 1
你可以将计数器作为第四个参数传递(初始值为0)。从perms返回它,并将其设置为内部调用返回的值。
英文:
You can pass the counter as the fourth argument (using 0 as the initial value). Return it from perms and set it to the value returned from the inner call.
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;
}
答案2
得分: 1
不需要静态计数器或将计数器值传递给每个方法调用。请注意,您的实现计算所有排列而不是唯一排列(字符串 "aab" 返回 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;
}
英文:
Without the need for a static counter or passing a counter value to each method call. Note that your implementation counts all permutations and not unique permutations (String "aab" returns 6, not 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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论