์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[๋ฐฑ์ค€(BOJ)] 9095๋ฒˆ: 1, 2, 3 ๋”ํ•˜๊ธฐ (Dynamic Programming, C++)

PROGRAMMING/Algorithm

by koharin 2021. 2. 11. 12:58

๋ณธ๋ฌธ

728x90
๋ฐ˜์‘ํ˜•

๐Ÿ“ ๋ฌธ์ œํ’€์ด ๊ณผ์ •


1 = 1 (1๊ฐ€์ง€) DP[0] = 1

2 = 1 + 1 = 2 (2๊ฐ€์ง€) DP[1] = 2

3 = 1 + 1 + 1 = 1 + 2 = 2 + 1 = 3 (4๊ฐ€์ง€) DP[2] = 4

4 = 1 + 1 + 1 + 1 = 1 + 1 + 2 = 1 + 2 + 1 = 1 + 3 = 2 + 1 + 1 = 2 + 2 = 3 + 1 (7๊ฐ€์ง€) DP[3] = 7

๋”ฐ๋ผ์„œ ์ ํ™”์‹์€ DP[i] = DP[i-3] + DP[i-2] + DP[i-1]

 

๐Ÿ’ป C++ ์ œ์ถœ์ฝ”๋“œ


#include <stdio.h>
#include <vector>
using namespace std;

int main(){
    int T;
    scanf("%d", &T);
    for(int i=0; i<T; i++){
        int n;
        scanf("%d", &n);
        vector<int> DP(n);
        
        DP[0] = 1; DP[1] = 2; DP[2] = 4;
        
        for(int j=3; j<n; j++){
            DP[j] = DP[j-2] + DP[j-1] + DP[j-3];
        }
        
        printf("%d\n", DP[n-1]);
    }
}
  • DP๋Š” ๋ฐฐ์—ด, vector, deque ์•„๋ฌด๊ฑฐ๋‚˜ ์ƒ๊ด€์—†๋‹ค.

 

๐Ÿ‘ ๊ฒฐ๊ณผ


728x90
๋ฐ˜์‘ํ˜•

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ