반응형

https://www.acmicpc.net/problem/4150

 

4150번: 피보나치 수

피보나치 수열은 다음과 같이 그 전 두 항의 합으로 계산되는 수열이다. 첫 두 항은 1로 정의된다. f(1) = 1, f(2) = 1, f(n > 2) = f(n − 1) + f(n − 2) 정수를 입력받아, 그에 해당하는 피보나치 수를 출력

www.acmicpc.net

https://www.acmicpc.net/problem/1003

 

1003번: 피보나치 함수

각 테스트 케이스마다 0이 출력되는 횟수와 1이 출력되는 횟수를 공백으로 구분해서 출력한다.

www.acmicpc.net

 

 

해결 방법 : DP

  • 가장 기초적인 DP 구현이다.
import sys
input = sys.stdin.readline

def solution(N):
    D = [0] * (N + 1) # dp table
    D[0] = D[1] = 1 # 초기값
    for i in range(2, N): # dp
        D[i] = D[i-1] + D[i-2]

    return D[N-1]

if __name__ == '__main__':
    N = int(input())
    result = solution(N)
    print(result)

 

해결 방법 : DP

  • 생각을 조금만 해보면 위 문제와 다를게 없을 것이다
import sys
input = sys.stdin.readline

def solution(N):
    D = [0] * (N + 1) # dp table
    D[0], D[1],  = (1, 0), (0, 1) # 초기값
    for i in range(2, N): # dp
        D[i] = (D[i-1][0] + D[i-2][0], D[i-1][1] + D[i-2][1])

    return D

if __name__ == '__main__':
    T = int(input())
    N = [int(input()) for _ in range(T)]
    result = solution(41) # 최대 경우의 dp table 생성
    for n in N:
        print(*result[n])
반응형

+ Recent posts