코딩테스트-알고리즘/백준 BOJ
[백준 BOJ/Silver III] 9095번 : 1, 2, 3 더하기
닉네임생각즁
2024. 1. 27. 10:21
https://www.acmicpc.net/problem/9095
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보다 작으면 다음을 더 탐색해보면 된다