본문 바로가기
Research/Data structure & algorithm

recursion

by RIEM 2023. 12. 9.

What is recursion

Recursion is the fuction that calls itself. This is good tool to solve the big problem with divide and conquer approach.

Rules

  1. Exit condition : stack overflow can occurs if there is no exit condition
  2. Divide-and-conquer approach

Pibonacci

Basic

divide and conquer with $O(n^2)$ time complexity

function getNthFibo(n) {
  if (n <= 1) {
    return n
  } else {
    return getNthFibo(n - 1) + getNthFibo(n - 2);
  } 
}
console.log(getNthFibo(3))

tail recursion

time complexity : $O(n)$
space complexity : $O(n)$

function getNthFiboBetter(n, lastlast, last) {
  if (n == 0) {
    return lastlast;
  }
  if (n == 1) {
    return last;
  }
  return getNthFiboBetter(n-1, last, lastlast + last)
}

Pascal's triangle

Pascal's triangle is consisted of values that is sum of two values located above.

'Research > Data structure & algorithm' 카테고리의 다른 글

fundamentals of sorting  (0) 2023.12.09
comparison-based sort  (0) 2023.12.09
시간복잡도와 공간복잡도  (0) 2023.03.18
01. Array 배열의 정의와 구현(JS)  (0) 2023.02.05
s15. Algorithm: Dynamic Programming  (0) 2022.12.03

댓글