문제 링크: https://www.acmicpc.net/problem/9095
9095번: 1, 2, 3 더하기
문제 정수 4를 1, 2, 3의 합으로 나타내는 방법은 총 7가지가 있다. 합을 나타낼 때는 수를 1개 이상 사용해야 한다. 1+1+1+1 1+1+2 1+2+1 2+1+1 2+2 1+3 3+1 정수 n이 주어졌을 때, n을 1, 2, 3의 합으로 나타내는 방법의 수를 구하는 프로그램을 작성하시오. 입력 첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있고, 정수 n이 주어진다. n은 양수이며 11보다 작다. 출력 각
www.acmicpc.net
주어진 숫자 n을 1, 2, 3의 합으로 표현할수 있는 방법의 수를 구하는 문제이다.
int 값을 리턴하는 재귀함수를 이용하여 구현했다.
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
|
#include <bits/stdc++.h>
using namespace std;
int t, n;
int solve(int sum) {
int ret = 0;
if(sum > n) return 0;
if(sum == n) return 1;
for(int i = 1; i <= 3; i++) {
ret += solve(sum + i);
}
return ret;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> t;
while(t--) {
cin >> n;
cout << solve(0) << '\n';
}
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
void형 재귀함수를 이용해서도 구현해봤다.
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
|
#include <bits/stdc++.h>
using namespace std;
int t, n, ans;
void solve(int sum) {
if(sum > n) return;
if(sum == n) ans++;
for(int i = 1; i <= 3; i++)
solve(sum + i);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> t;
while(t--) {
cin >> n;
ans = 0;
solve(0);
cout << ans << '\n';
}
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
'재귀, 백트래킹 (Recursion, Backtracking)' 카테고리의 다른 글
백준 14501 퇴사 (0) | 2020.05.08 |
---|---|
백준 1759 암호 만들기 (0) | 2020.05.05 |
백준 6603 로또 (0) | 2020.05.05 |
백준 10971 외판원 순회 2 (0) | 2020.05.04 |
백준 10819 차이를 최대로 (0) | 2020.05.04 |