【算法】递归算法举例

Java实现
//n阶乘 递归算法
    public static int fact(int n)
    
{
        
int ans;
        
if(n==0||n==1)
        
{
            ans
=1;
        }

        
else
        
{
            ans
=n*fact(n-1);
        }

        
return(ans);
    }

    
//n阶乘 非递归算法<<
    public static int fact1(int n) throws Exception
    
{
        
if(n<0)
        
{
            
throw(new Exception("不能求<0的整数的阶乘!"));
        }

        
int sum=1;
        
if(n>1)
        
{
            
for(int i=2;i<=n;i++)
            
{
                sum
*=i;
            }

        }

        
return(sum);
    }

    
    
//斐波那契数 递归程序
    public static int fibon(int n)
    
{
        
int ans;
        
if(n==0||n==1)
        
{
            ans
=1;
        }

        
else
        
{
            ans
=fibon(n-1)+fibon(n-2);
        }

        
return(ans);
    }

    
//斐波那契数 非递归程序
    public static int fibon1(int n)
    
{
        
int backitem1=1;
        
int backitem2=1;
        
int thisitem=1;
        
if(n>1)
        
{
            
for(int i=2;i<=n;i++)
            
{
                thisitem
=backitem1+backitem2;
                backitem2
=backitem1;
                backitem1
=thisitem;
            }

        }

        
return(thisitem);
    }

    
    
//汉诺塔问题 递归程序
    public static void HanoiTower(int n,char from,char aux,char to)
    
{
        
if(n==1)
        
{
            System.out.print(
"Move disk "+n+" from "+from+"->"+to+"\n");
        }

        
else
        
{
            HanoiTower(n
-1,from,to,aux);
            System.out.print(
"Move disk "+n+" from "+from+"->"+to+"\n");
            HanoiTower(n
-1,aux,from,to);
        }

    }

posted on 2009-04-25 23:43 intrl 阅读(2112) 评论(2)  编辑 收藏 引用 所属分类: 数据结构与算法

评论

# re: 【算法】递归算法举例 2009-04-30 23:42 风花雪月

你java数据结构学的不错啊!!!  回复  更多评论   

# re: 【算法】递归算法举例 2009-05-27 15:33 intrl

@风花雪月
谢谢!
  回复  更多评论   

只有注册用户登录后才能发表评论。
<2009年4月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

导航

统计

随笔分类(55)

随笔档案(34)

网址收藏

资源下载

随笔导航

搜索

最新评论

阅读排行榜

评论排行榜