-
[JS] 재귀 함수(Recursive Function)Algorithm & Data Structure 2022. 1. 31. 17:26SMALL
freecodecamp를 통해 자스 문법을 배우고 있는 요즘,
재귀 파트를 시작했는데 넘나 어려운 것..
포스팅으로 정리해보고자 한다.
function sum(arr, n) { // Only change code below this line if (n<=0){ return 0; } else { return sum(arr,n-1)+arr[n-1]; } // Only change code above this line }
재귀 함수는 말 그대로 자기 자신을 불러오는 함수이기 때문에 그냥 호출하면 끊임없이 실행된다.
따라서 멈춰야 하는 경우를 반드시 만들어야 하는데 그 경우를 base case라고 한다. 위의 예시에선 if (n<=0) 이 해당된다.
//for문 function multiply(arr, n) { let product = 1; for (let i = 0; i < n; i++) { product *= arr[i]; } return product; } //재귀 function multiply(arr, n) { if (n <= 0) { return 1; } else { return multiply(arr, n - 1) * arr[n - 1]; } }
// ex1 function countdown(n){ if (n<1) { return []; } else { const countArray = countdown(n-1); countArray.unshift(n); return countArray } } //ex2 function countup(n) { if (n < 1) { return []; } else { const countArray = countup(n - 1); countArray.push(n); return countArray; } } console.log(countup(5)); //[1,2,3,4,5]
say you want to write a recursive function that returns an array containing the numbers 1 through n. This function will need to accept an argument, n, representing the final number. Then it will need to call itself with progressively smaller values of n until it reaches 1.
(free code camp 설명)
1부터 n까지 포함하는 배열을 리턴하는 재귀함수를 쓸 때, 함수는 인수 n을 필요로 하며, 이 n은 final number를 의미한다. 그리고 나서 함수는 1에 도달할 때까지 순차적으로 작아지는 n과 함께 자기 자신을 호출할 것이다.
cf. 백준 10872 파이썬
def factorial(n): if n <= 0: return 1 return factorial(n-1) * n N = int(input()) print(factorial(N))
자바스크립트
function factorial(n) { if(n<1) { return 1; } else { return factorial(n-1) * n; } }
반응형'Algorithm & Data Structure' 카테고리의 다른 글
[JS]어쩌다 까먹는 자바스크립트 배열 메소드/함수 총정리 (0) 2022.03.13 [JS/Node.js] readline을 통한 입출력 (0) 2022.03.12 [JS] Getter와 Setter (0) 2022.01.25