코드의 가독성을 향상시키고 로직을 단순화할 수 있다.public class Staircase {
public static int countWays(int n) {
if (n == 0 || n == 1) {
return 1;
}
int a = 1, b = 1;
for (int i = 2; i <= n; i++) {
int temp = b;
b += a;
a = temp;
}
return b;
}
public static void main(String[] args) {
int stairs = 5;
System.out.println("Number of ways = " + countWays(stairs));
}
}
public class Staircase {
public static int countWays(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return countWays(n - 1) + countWays(n - 2);
}
}
public static void main(String[] args) {
int stairs = 5;
System.out.println("Number of ways = " + countWays(stairs));
}
}
무한 루프를 방지하기 위해 재귀 함수는 반드시 종료 조건을 포함해야 한다.스택 오버플로우를 일으킬 수 있다.반복문에 비해 더 많은 메모리 사용과 수행 시간을 필요로 할 수 있다.int factorial(int n)
{
if (n == 0)
return 1;
return n * factorial(n-1);
}
factorial(3)을 실행한 경우 Stack Memory

ref.
https://velog.io/@kai6666/%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98-%EC%9E%AC%EA%B7%80-%ED%95%A8%EC%88%98-Recursion
https://gomguard.tistory.com/111