https://www.acmicpc.net/problem/9095
9095번: 1, 2, 3 더하기
각 테스트 케이스마다, n을 1, 2, 3의 합으로 나타내는 방법의 수를 출력한다.
www.acmicpc.net
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static int[] num = {1, 2, 3};
public static int count;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int T = Integer.parseInt(st.nextToken());
for(int index = 0; index < T; index++) {
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
count = 0;
sum(0, n);
System.out.println(count);
}
}
public static void sum(int result, int n) {
for(int i = 0; i < num.length; i++) {
if(result == n) {
count++;
return;
} else if (result > n) {
return;
} else {
sum(result + num[i], n);
}
}
}
}
짝지을 수 있는 모든 경우를 보면서 합이 n이 되면 count를 세주고, n보다 크다면 더이상 볼게 없으니 return해서 돌아가고 n보다 작으면 다음을 더 탐색해보면 된다
'코딩테스트-알고리즘 > 백준 BOJ' 카테고리의 다른 글
[백준 BOJ/Silver III] 14501번 : 퇴사 (1) | 2024.01.28 |
---|---|
[백준 BOJ/Silver IV] 11399번 : ATM (1) | 2024.01.27 |
[백준 BOJ/Silver III] 20920번 : 영단어 암기는 괴로워 (1) | 2024.01.25 |
[백준 BOJ/Silver IV] 11047번 : 동전 0 (1) | 2024.01.25 |
[백준 BOJ/Silver V] 2563번 : 색종이 (0) | 2024.01.23 |