[英]How to print the fibonacci sequence in reverse order WITHOUT using a loop
我在接受采访时得到了这个问题。 在面试官要我不使用我在打印方法中使用的循环时,这很容易。 术语数是一个输入,当它是7时,例如:print 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();
}
}
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);
测试printReversedFib(7);
将打印:
13
8
5
3
2
1
1
据推测,你可以做一个递归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
我做了相反的方式。 谁能提升它? 欢迎所有建议。
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 610 377 233 144 89 55 34 21 13 8 5 3 2 1
干杯!
您可以使用DP(动态程序)轻松解决此问题。您需要做的就是创建DP阵列,然后您可以按相反顺序迭代阵列。 以下是Go中的解决方案。 http://play.golang.org/p/3m1n_AUSZl
func FibPrintRev(n int) {
space := make([]int, n+1)
// base case
space[1] = 1
space[2] = 1
// Create dp array
for i := 3; i <= n; i++ {
space[i] = space[i-1] + space[i-2]
}
// Iterate in rev. order
for i := n; i > 0; i-- {
fmt.Println(space[i])
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.