record logo record

재귀란?

//재귀
public static int recursive(int n) {
    if(n == 1) return 1;
    return n * recursive(n-1);
}

꼬리재귀란?

재귀와 꼬리재귀

public class Factorial {
    //재귀
    public static int recursive(int n) {
        if(n == 1) return 1;

        return n * recursive(n-1);
    }
    
    //꼬리재귀
    public static int tailRecursive(int n, int acc) {
        if(n == 1) return acc;

        return tailRecursive(n-1, n*acc);   
    }
}

재귀와 꼬리 재귀 차이점

algorithm-recursive_tailrecursive_1