逻辑有点乱了!!!!!

墙角在唱歌 2012-09-17 10:32:17
第一个月为1 第二个月为1 第三个月为2 第四个月为3 第五个月为5 规律是从第三个月起 每个月都是前两个月之和??
求思路 用代码怎么表示?????
...全文
165 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
keithcai 2012-09-17
  • 打赏
  • 举报
回复
迭代的复杂度为O(N)
keithcai 2012-09-17
  • 打赏
  • 举报
回复
2楼就是用迭代的嘛,但是不能算前两项,所以看我的吧

public static void main(String args[]) {
static int N=10;
int i=0,j=1;
for(int m=1;m<N;m++){
j=i+j;
i=j-i
System.out.println(j);
}
}
见习老狼 2012-09-17
  • 打赏
  • 举报
回复
用递归
package com.itcast;

public class Test8 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int x=xx(5);
System.out.println(x);
}

public static int xx(int n){
if(n==1||n==2){
return 1;
}else{
return xx(n-1)+xx(n-2);
}
}

}
keithcai 2012-09-17
  • 打赏
  • 举报
回复

果然是算法没学好呀,算法第二章就是说的递归算斐波纳契数列效率低下,复杂度为O((3/2)^N)呈指数增长的,所以要用迭代做呀~~~~同学你还是看书吧~
你那个问题就是生兔子问题嘛~很简单的呀
xiars123 2012-09-17
  • 打赏
  • 举报
回复
public class Test {
public static void main(String[] args) {
int[] month = new int[12];
month[0] = 1;
month[1] = 1;
System.out.print(month[0] + " " + month[1] + " ");
for (int i = 2; i < month.length; i++) {
month[i] = month[i - 1] + month[i - 2];
System.out.print(month[i] + " ");
}
}
}

自己设个断点debug一下,看看具体怎么实现的,就一个循环的逻辑。
keithcai 2012-09-17
  • 打赏
  • 举报
回复
Fibonacci Sequence(斐波纳契数列)
这个应该是算法第2章就提到的内容吧。。。。翻翻书呗
xiars123 2012-09-17
  • 打赏
  • 举报
回复
public class Test {
public static void main(String[] args) {
int[] month = new int[12];
month[0] = 1;
month[1] = 1;
System.out.print(month[0] + " " + month[1] + " ");
for (int i = 2; i < month.length; i++) {
month[i] = month[i - 1] + month[i - 2];
System.out.print(month[i] + " ");
}
}
}
Robbie枫叶EX 2012-09-17
  • 打赏
  • 举报
回复
用个数组装数据,args[0]和args[1]都赋值1,然后用一个for语句.
for(int i = 2; i < n; i++)
args[i] = args[i-1] + args[i-2];
wang_sjiao 2012-09-17
  • 打赏
  • 举报
回复
public static void main(String args[]) {
int i=1,j=1;
for(int m=0;m<10;m++){
int k=i+j;
j=i;
i=k;
System.out.println(k);
}
}
balabala_sean 2012-09-17
  • 打赏
  • 举报
回复
int x = [1,1,2,3,5,······];

第n个月的:

int value = x[n-2]+x[n-3];



Mourinho 2012-09-17
  • 打赏
  • 举报
回复

static int getSum(int mouth){
if(mouth < 1){
//handle exception here
}
return (mouth == 1 || mouth == 2) ? 1 : getSum(mouth - 1) + getSum(mouth - 2);
}

flyoversky 2012-09-17
  • 打赏
  • 举报
回复
斐波纳契数列

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧