백준 15652 N과 M (4)
1. 문제 링크
https://www.acmicpc.net/problem/15652
2. 문제 해결에 대한 아이디어
- 중복 조합이므로 조합 로직에서 visit을 제외하였다.
- Input에 따라 Output 양이 많아져서, StringBuilder를 사용하여 시간을 줄일 수 있다.
3. 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N, M;
static int[] nums;
static int[] candidate;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] nm = br.readLine().split(" ");
N = Integer.parseInt(nm[0]);
M = Integer.parseInt(nm[1]);
nums = new int[N];
candidate = new int[M];
for (int i = 0; i < N; i++) {
nums[i] = i + 1;
}
combination(0, 0);
System.out.print(sb);
}
static void combination(int depth, int start) {
if (depth == M) {
for (int i = 0; i < M; i++) {
sb.append(candidate[i]).append(" ");
}
sb.append("\n");
return;
}
/**
* 중복을 허용하기 때문에 visit 을 따로 체크하지 않는다.
*/
for (int i = start; i < N; i++) {
candidate[depth] = nums[i];
combination(depth + 1, i);
}
}
}
4. 채점 결과
5. 느낀 점
- 중복 조합은 일반 조합과 달리 visit을 사용하지 않는다.
- Output이 많은 경우, StringBuilder를 적극 활용하자
'알고리즘 > 백준 - 실버' 카테고리의 다른 글
백준 15655 N과 M (6) (0) | 2022.01.03 |
---|---|
백준 15654 N과 M (5) (0) | 2022.01.02 |
백준 15651 N과 M (3) (0) | 2021.12.31 |
백준 15650 N과 M (2) (0) | 2021.12.30 |
백준 15649 N과 M (1) (0) | 2021.12.29 |
댓글