Problem
https://www.acmicpc.net/problem/9095
9095번: 1, 2, 3 더하기
각 테스트 케이스마다, n을 1, 2, 3의 합으로 나타내는 방법의 수를 출력한다.
www.acmicpc.net
Solution
#include<iostream>
#include<string.h>
using namespace std;
int t; // 테스트케이스 수
int n; // 정수 n
int cache[12]; // 방법의 수 저장
int main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
memset(cache,0,sizeof(int)); // 메모리 초기화
cache[1]=1;
cache[2]=2;
cache[3]=4;
cin >> t;
for(int i=0;i<t;i++){
cin >> n;
for(int i=4;i<=n;i++){
cache[i]=cache[i-1]+cache[i-2]+cache[i-3];
}
cout << cache[n] << '\n';
}
return 0;
}
이 문제는 dp 알고리즘으로 풀수 있다. 각각의 경우의 수에 대한 예상 결과값을 확인하고 규칙이 발견되면 위와 같이 점화식을 세울 수 있다.
Reference
https://sanghyu.tistory.com/108
[백준/C++] 9095번: 1,2,3 더하기 (DFS/DP)
1) DFS (모든 조합 체크) #include using namespace std; int test_case, N; int cnt = 0; void solve(int sum) { if (sum == N) { cnt++; return; } if (sum > N) return; for (int i = 1; i > test_case; for (int i = 0; i < test_case; i++) { cin >> N; solve(0);
sanghyu.tistory.com
'코딩 테스트 > 백준 (C++, Python)' 카테고리의 다른 글
cpp) 백준 1966: 프린터 큐 (0) | 2023.07.17 |
---|---|
cpp) 백준 1463: 1로 만들기 (0) | 2023.07.15 |
cpp) 백준 11399: ATM (0) | 2023.07.12 |
cpp) 백준 18258: 큐 2 (0) | 2023.07.12 |
cpp) 백준 10773: 제로 (0) | 2023.07.08 |