Java中使用递归的不同方式 [英] Different ways of using recursion in Java
本文介绍了Java中使用递归的不同方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在考虑几种优雅的方式来用 Java 编写一个简单的类似 Lisp 的递归函数,比如简单的求和.
I'm thinking of several elegant ways of writing a simple Lisp-like recursive function in Java that does, let's say, a simple summation.
在 Common Lisp 中,它会是这样的:
In Common Lisp it would be like this:
(defun summation(l)
(if l
(+ (car l) (summation (cdr l)))
0))
(summation '(1 2 3 4 5)) ==> 15
在 Java 中,许多可能的解决方案之一是:
In Java the one of many possible solutions would be:
public int summation(int[] array, int n) {
return (n == 0)
? array[0]
: array[n] + summation(array, n - 1);
}
CALL:
summation(new int[]{1,2,3,4,5}, 4); //15
1) 有没有办法不使用索引 n?
1) Is there any possible way NOT to use the index n?
2) 或者留下您认为有趣的解决方案(非迭代).
2) Or leave your solution (non-iterational) which you see as interesting.
谢谢.
推荐答案
如果使用 List.subList 方法,它可能会在下面执行迭代.您可以改用 Queue 以避免迭代.例如:
If you use List.subList method, it may perform iteration, underneath. You can use Queue instead, to avoid iteration. For example:
public int sum(Queue queue) {
return queue.isEmpty() ? 0 : (queue.poll() + sum(queue));
}
这篇关于Java中使用递归的不同方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文