欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

n的阶乘-递归-动态规划

程序员文章站 2024-03-15 18:54:48
...

递归:

public class Factorial {
    public int factorial(int n){
        if(n<0)
            return -1;
        else if(n==0)
            return 1;
        return n*factorial(n-1);
    }
    public static void main(String[] args){
        Factorial fac=new Factorial();
        System.out.print(fac.factorial(5));
    }
}

动态规划
自顶向下:

public class Factorial {
    public static int[] result;
    public int solve(int n){
        if(result[n]>=0)
            return result[n];
        result[n]=n*solve(n-1);
        return result[n];
    }
    public int factorial(int n){
        if(n<0)
            return -1;
        else if(n==0)
            return 1;
        result=new int[n+1];
        result[0]=1;
        for(int i=1;i<result.length;i++){
            result[i]=-1;
        }
        return solve(n);
    }
    public static void main(String[] args){
        Factorial fac=new Factorial();
        System.out.print(fac.factorial(5));
    }
}

自底向上:

public class Factorial {
    public int factorial(int n){
        if(n<0)
            return -1;
        else if(n==0)
            return 1;
        int[] result=new int[n+1];
        result[0]=1;
        for(int i=1;i<result.length;i++){
            result[i]=i*result[i-1];
        }
        return result[result.length-1];
    }
    public static void main(String[] args){
        Factorial fac=new Factorial();
        System.out.print(fac.factorial(5));
    }
}
相关标签: n的阶乘