자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.
1부터 N까지 자연수 중에서 M개를 고른 수열
같은 수를 여러 번 골라도 된다.
첫째 줄에 자연수 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 7)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다.
수열은 사전 순으로 증가하는 순서로 출력해야 한다.
- 백트래킹
import java.util.*;
import java.io.*;
public class Main {
public static int arr[];
public static int N, M;
public static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
arr = new int[M];
DFS(0);
System.out.println(sb);
}
public static void DFS(int depth) {
if(depth == M) {
for(int i=0; i<M; i++)
sb.append(arr[i]).append(' ');
sb.append('\n');
return;
}
for(int i=1; i<=N; i++) {
arr[depth] = i;
DFS(depth + 1);
}
}
}
DFS로 문제를 해결했다.
가장 처음으로 탐색할 노드는 모든게 1인 11111... 일 것이고
그 다음 탐색 노드는 111... 112 일 것이다.중복이 허용되기 때문에 다른 특별한 장치나 조건 없이, 처음부터 끝노드 까지 반복하면 된다.