我在一次面试中得到了这个问题。这很容易,直到面试官不让我使用打印方法中使用的循环。字数是输入,例如:打印13 8 5 3 2 1 1。他说用Python很容易,但我也可以用Java编写机制,但我想不出他指的是哪一种机制。谢谢!
我的Java代码:
public class Fibonacci {
private int[] a;
private int fib(int i) {
assert (i>=0);
if (a[i]==0) {
if (i==0 || i==1) {
a[i] = 1;
} else {
a[i] = fib(i - 2) + fib(i - 1);
}
}
return a[i];
}
public Fibonacci(int numberTerms) {
if (numberTerms<2) throw new IllegalArgumentException("expect at least 2 terms for a Fibonacci sequence");
a = new int[numberTerms];
}
public void print() {
for (int i=a.length; i!=0; i--) {
System.out.println(fib(i-1));
}
}
public static void main(String[] args) {
Fibonacci f = new Fibonacci(7);
f.print();
}
}发布于 2014-09-14 18:07:27
想必,您可以做一个递归的print;就是这样-
public void print() {
for (int i=a.length; i!=0; i--) {
System.out.println(fib(i-1));
}
}可能是这样,
public void print() {
print(a.length - 1);
}和
public void print(int i) {
if (i > 0) {
System.out.println(fib(i - 1));
print(i - 1);
}
}当我运行上面的内容时,我得到请求的输出
13
8
5
3
2
1
1发布于 2014-09-14 18:32:28
public static int f(int n){
if (n <= 1)
return n;
else
return f(n-1) + f(n-2);
}
static void printReversedFib(int x){
if(x <= 1)
System.out.println(f(x));
else{
System.out.println(f(x));
printReverseFib(x-1);
}
}使用printReversedFib(7);进行的测试将打印:
13
8
5
3
2
1
1发布于 2015-08-21 08:27:51
我是这样做的。谁能加强它呢?欢迎所有建议。
package com.jbjares.dynamicProgramming;
public class Fibonacci {
public static void main(String[] args) {
new Fibonacci().calc(317811,1);
}
public void calc(Integer start,Integer end){
Integer f = (int) (start/((1+Math.sqrt(5))/2));
System.out.println(f);
if(f==end){
return;
}
calc(++f,end);
}
}结果: 196417 121393 75025 46368 28657 17711 10946 6765 4181 2584 1597 987 377 377 233 144 89 34 21 13 8 5 3 2 1
干杯!
https://stackoverflow.com/questions/25836313
复制相似问题