java代码实现前两个数相加=第三个,只使用一次递归的谁能帮我实现

wyh916427630 2014-10-26 11:09:47
public class test {

public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub

int n=10;

int[] a=new int[2];
int temp=0;
for(int i=0;i<n;i++){

//temp=getint(i);

//System.out.print(getint(i)+" ");
//System.out.print(getint1(i,a)+" ");
System.out.print(getint2(i,temp)+" ");

}

}
/**
* 使用递归
* @param n
* @return
*/
public static int getint(int n){

if(n==0){

return 0;

}else if(n==1){

return 1;

}else{

return getint(n-1)+getint(n-2);
}

}
/**
* 只使用一次递归
* @param n
* @return
*/
public static int getint2(int n,int temp){

if(n==0){
temp=0;
return 0;

}else if(n==1){
temp=1;
return 1;

}else{
temp=getint(n-2);
return temp+getint(n-2);
}

}
/**
* 使用数组的方式
* @param n
* @param a
* @return
*/
public static int getint1(int n,int[] a){
int tmp=0;
if(n==0){
a[0]=0;
return 0;

}else if(n==1){
a[1]=1;
return 1;

}else{
tmp=a[1];
a[1]+=a[0];
a[0]=tmp;
return a[1];
}

}

}
...全文
946 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
healer_kx 2014-10-30
  • 打赏
  • 举报
回复
Python 非递归的解法。 http://blog.chinaunix.net/uid-181040-id-2839050.html 对Java代码有借鉴意义。
GL1271374353 2014-10-30
  • 打赏
  • 举报
回复
lliiqiang 2014-10-28
  • 打赏
  • 举报
回复

int get(int n){
if(n<=2)
return 1;
return get(n-1)+get(n-2);
}
Mr_JieLQ 2014-10-26
  • 打赏
  • 举报
回复
所谓一次递归就是尾递归

int factorial_tail(int n,int acc1,int acc2)
{
    if (n < 2)
    {
        return acc1;
    }
    else
    {
        return factorial_tail(n-1,acc2,acc1+acc2);
    }
}
日知己所无 2014-10-26
  • 打赏
  • 举报
回复
是斐波那契数列吗?这里有个更复杂些的例子: http://bbs.csdn.net/topics/390903374 不用递归也挺好,执行速度快,而且在处理很大很大的数的时候不会“溢出” 另外,有一些网站挺好的,经典的算法都有各种编程语言的标准的解决示例,可以参考 http://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Fibonacci_Number_Program

62,614

社区成员

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

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