티스토리 뷰
The Fibonacci Sequence
The Fibonacci sequence appears in nature all around us, in the arrangement of seeds in a sunflower and the spiral of a nautilus for example.
The Fibonacci sequence begins with fibonacci(0) = 0 and fibonacci(1) = 1 as its first and second terms. After these first two elements, each subsequent element is equal to the sum of the previous two elements.
Programmatically:
- fibonacci(0) = 0
- fibonacci(1) = 1
- fibonacci(n) = fibonacci(n - 1) + fibonacci(n - 2)
Given n, return the n^th number in the sequence.
As an example, n = 5. The Fibonacci sequence to 6 is fs = [0, 1, 1, 2, 3, 5, 8]. With zero-based indexing, fs[5] = 5
Recursion: Fibonacci Numbers | HackerRank
Compute the n'th Fibonacci number.
www.hackerrank.com
풀이
function fibonacci(n) {
if(n === 0) return 0;
if(n === 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
생각보다 너무 간단해서 허무쓰....
재귀함수로 이전값과 전전값을 더해준 걸 리턴해주면 끝.
단, 0과 1은 각각 0과 1을 반환함.
다른 사람의 풀이
const fibonacci = (n, cache = {}) => {
if (n < 0 || n === undefined) return null;
if (n < 2) return n;
if (cache[n]) return cache[n];
cache[n] = fibonacci(n - 1, cache) + fibonacci(n - 2, cache);
return cache[n];
};
재귀함수를 이용했는데, n이 음수이거나 정의되지 않았을 때를 처리해줬고, 내가 if문 두개로 나눠쓴 것을 n < 2일 때, n을 반환하는 식으로 한 번에 처리함.
const fibonacci = n => {
let previous = 0;
let current = 1;
if (n < 0 || n === undefined) return null;
if (n < 2) return n;
for (let i = 1; i < n; i++) {
let temp = current;
current = current + previous;
previous = temp;
}
return current;
};
같은 사람의 다른 풀이인데, 재귀함수를 이용하지 않고, previous와 current 변수를 만들고 for문을 돌려 처리를 함.
작성자피셜 : "Better solution since it has a constant space complexity but still has linear time complexity"
'1Day 1Algorithm' 카테고리의 다른 글
[DAY 8] Greedy Florist (0) | 2019.10.08 |
---|---|
[DAY 7] A Very Big Sum (0) | 2019.10.07 |
[DAY 5] Flipping bits (0) | 2019.10.05 |
[DAY 4] Bitwise Operators (0) | 2019.10.04 |
[DAY 3] Compare the Triplets (0) | 2019.10.03 |
- Total
- Today
- Yesterday
- 구간합
- Typescript
- 알고리즘
- 배열
- Array
- 자바스크립트
- Algorithm
- greedyAlgorithm
- 시분할시스템
- 배치처리시스템
- sort()
- Webpack
- 자료구조
- Props
- 1day1algorithm
- OS
- 프로그래머스
- js
- 웹팩
- 컴퓨터공학
- React
- 운영체제
- 타입스크립트
- 멀티프로그래밍
- 리액트
- redux-saga
- javascript
- reduce()
- 우아한테크러닝
- sort
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |