문제/백준_자바
120. 15650(N과M (4))
sm_hope
2022. 6. 29. 11:17
import java.util.*;
import java.io.*;
class Main {
static StringBuilder sb = new StringBuilder();
static int N, M;
static int[] arr;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] sBits = br.readLine().split(" ");
N = Integer.parseInt(sBits[0]);
M = Integer.parseInt(sBits[1]);
arr = new int[M];
DFS(1, 0);
System.out.println(sb);
}
private static void DFS(int start, int depth) {
if (depth == M) {
for (int val : arr) {
sb.append(val + " ");
}
sb.append("\n");
return;
}
for (int i = start; i <= N; i++) {
arr[depth] = i;
DFS(i, depth + 1);
}
}
}
문제요약
DFS를 이용하여 백트래킹을 해보아라.
설명
DFS와 백트래킹에 대한 개념은 아래를 참고하자.
https://smhope.tistory.com/309
백트래킹
백트래킹 더 이상 나아갈 수 없는 상황에서 그 이전 단계로 복귀하는 과정 모든 경우의 수를 전부 고려하는 알고리즘이다. 트리 탐색 알고리즘이라고 봐도 무방하며 방식에 따라 깊이우선탐색 (
smhope.tistory.com
https://smhope.tistory.com/307
깊이 우선 탐색(DFS)
깊이 우선 탐색(DFS) -> 스택 사용 (재귀 이용 -> 재귀 자체가 스택임) 루트노드에서 시작해서 다음 분기로 넘어가기 전에 해당 분기를 완벽하게 탐색하는 방법 특징 깊이 우선 탐색(DFS) 에 비해서
smhope.tistory.com
매우 간단한 문제