<p>使用<code>Pair</code>类:</p>
<pre><code>class Pair {
private int first;
private int second;
// getters, setters, constructor
}
</code></pre>
<p>本部分:</p>
<pre><code>def fib(n):
## Handle special case when n == 0
if n == 0:
return 0
## General case, return the first of the
## two values returned by fibaux
else:
return fibaux(n)[0]
</code></pre>
<p>可以“翻译”为:</p>
<pre><code>int fib(int n) {
// Handle special case when n == 0
if (n == 0) {
return 0;
}
// General case, return the first of the
// two values returned by fibaux
else {
return fibaux(n).getFirst();
}
}
</code></pre>
<p>这一部分:</p>
<pre><code>## Auxiliary function
## Return the nth and (n-1)th Fibonacci numbers
## n must be an integer >= 1
def fibaux(n):
## Base case of for recursion
if n == 1:
return 1, 0
else:
## Recursive case
f2, f1 = fibaux(n - 1) ## **this is the part I cant figure out in java**
return f2 + f1, f2
</code></pre>
<p>收件人:</p>
<pre><code>// Auxiliary function
// Return the nth and (n-1)th Fibonacci numbers
// n must be an integer >= 1
Pair fibaux(int n):
// Base case of for recursion
if (n == 1) {
return new Pair(1, 0);
} else {
// Recursive case
Pair next = fibaux(n - 1);
return new Pair(next.getFirst() + next.getSecond(), next.getFirst());
}
}
</code></pre>
<p>(<a href="https://ideone.com/mSE4vn" rel="nofollow">Demo</a>)</p>