[코테 풀이] Fibonacci Number

시내·2024년 7월 28일
0

Q_509) Fibonacci Number

출처 : https://leetcode.com/problems/fibonacci-number/

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n).

class Solution {
    public int fib(int n) {
        int[] fibb = new int[n + 1];
        if (n == 0) return 0;
        else if (n == 1) return 1;
        else {
            fibb[1] = 1;
            fibb[0] = 0;
            for (int i = 2; i <= n; i++) {
                fibb[i] = fibb[i - 1] + fibb[i - 2];
            }
            return fibb[n];
        }
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글