9095번: 1, 2, 3 더하기
각 테스트 케이스마다, n을 1, 2, 3의 합으로 나타내는 방법의 수를 출력한다.
www.acmicpc.net
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
static int num;
static int ans = 0;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testcase = Integer.parseInt(br.readLine());
List<Integer> checklist;
int[] arr = {1,2,3};
for(int i=0; i<testcase; i++){
checklist = new ArrayList<>();
num = Integer.parseInt(br.readLine());
ans = 0;
for(int j=1; j<=num; j++){
makeans(arr, checklist, j);
}
System.out.println(ans);
}
}
private static void makeans(int[] arr, List<Integer> checklist, int cnt){
if(checklist.size() == cnt){
int sum = 0;
for(int i=0; i<checklist.size(); i++){
sum += checklist.get(i);
}
if(sum == num)
ans++;
return;
}
for(int i=0; i<arr.length; i++){
checklist.add(arr[i]);
makeans(arr, checklist, cnt);
checklist.remove(checklist.size()-1);
}
}
}
중복순열을 이용했다.
1. arr[] = {1,2,3} 에서 1,2,3을 '자기 자신을 포함하고, 순서가 있도록' == (1,1)가능하고, (1,2)!=(2,1)
1~num개를 뽑는다.
2. 뽑은 숫자들의 합이 num이 되는 경우 ans++ 해준다.
** 중복순열 참고
순열 nPr
① 순열 : 순서O, 중복X ('중복'은 자기자신 포함 여부를 의미) 예) 1,2,3,4 중 2개 뽑는 경우 (1,2) (1,3) (1,4) (2,1) (2,3) (2,4) (3,1) (3,2) (3,4) (4,1) (4,2) (4,3) /* N : 총 숫자 개수(num.length)..
yeone2ee.tistory.com
'1d-1c > BOJ' 카테고리의 다른 글
11723_집합 (JAVA) (0) | 2020.11.25 |
---|---|
10972_다음 순열 & 10973_이전 순열 (JAVA) (0) | 2020.11.24 |
14500_테트로미노 (JAVA) (0) | 2020.11.23 |
6588_골드바흐의 추측 (JAVA) (0) | 2020.11.22 |
9613_GCD 합 (JAVA) (0) | 2020.11.22 |