[英]Removing Tail-Recursion from Method (Java)
I have this method: 我有这种方法:
private String computePerm(int iteration) {
if (iteration < n + 1) {
return Character.toString((char) (iteration + 48));
} else {
if (iteration % n == 0) {
return computePerm((iteration / n) - 1) + computePerm(((iteration - 1) % n + 1));
} else {
return computePerm(iteration / n) + computePerm(iteration % n);
}
}
}
It computes a permutation induced by a single breadth-first search traversal. 它计算由单个广度优先搜索遍历引起的排列。 I'm using it to solve Post's correspondence problem .
我正在用它来解决Post的对应问题 。 However, I suspect it is tail-recursive, and it seems to incur an ugly overhead on some instances of the problem.
但是,我怀疑它是尾递归的,并且在某些情况下似乎会产生难看的开销。
How can I remove tail-recursion while preserving the method's behavior? 如何在保留方法行为的同时删除尾递归?
This does what you're after (the permutation of an alphabet of size n ): 这就是您想要的(大小为n的字母排列):
private static String computePerm(int iteration) {
return Integer.toString(iteration, n);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.