티스토리 뷰
import java.util.Scanner;
public class Q1855 {
public int fibonacci(int n) {
/* Fibonacci sequence is a sequence f numbers where each number is a sum of two precedent numbers.
* Thus, sequence looks as follows: 1 1 2 3 5 8 13 21 34 ...
* For nth fibonacci number, the repetition occurs n times, each of which adds two numbers, starting from 0 and 1.
* e.g. 3rd fibonacci number: requires computing 0 + 1, namely, a sum of 1st and 2nd fibonacci numbers.
* In other words, nth fibonacci number is a sum of (n-2)th and (n-1)th fibonacci numbers.
* The only information we have is that first and second numbers of the sequence are 1.
* Therefore, we repeat as far as we get 0. This gives us a hint on how to set a base case and a return statement. */
if (n <= 2) return 1;
return fibonacci(n-2) + fibonacci(n-1);
// if n = 4, fibonacci(2) + fibonacci(3) = 1 + fibonacci(1) + fibonacci(2) = 1 + 1 + 1 = 3
}
public static void main(String[] args) {
Q1855 q1855 = new Q1855();
Scanner sc = new Scanner(System.in);
int order = sc.nextInt();
System.out.println(q1855.fibonacci(order));
}
}
Code snippets above is an example implementation of fibonacci sequence using recursive call of a method.
'Algorithms' 카테고리의 다른 글
[알고리즘] Dijkstra's algorithm 1부 - 이론 (0) | 2022.12.04 |
---|---|
[알고리즘] 에라토스테네스의 체 (0) | 2022.12.03 |
[알고리즘] Algorithms Study with JAVA - Backtracking (0) | 2022.11.18 |
[알고리즘] Quick Sort: 구현 (Array 2단계) (0) | 2022.11.17 |
[알고리즘] Quick Sort 이론 및 구현: List (0) | 2022.11.17 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 역직렬화
- Firebase
- 알고리즘
- ci/cd
- docker
- 깃랩
- json web token
- 지연 로딩
- 실시간데이터
- 인증/인가
- 가상 서버
- LazyInitializationException
- N+1
- DeSerialization
- 코테
- Spring Boot
- 기지국 설치
- Java Data Types
- JPA
- gitlab
- DTO
- 도커
- spring
- JOIN FETCH
- JPQL
- FCM
- Jackson
- 프로그래머스
- @RequestBody
- google cloud
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 | 31 |
글 보관함