Baekjoon Algorithm | Problem 15650: N and M (2)
Source
https://www.acmicpc.net/problem/15650
Problem
Solve Baekjoon Online Judge problem 15650, N and M (2).
Input
Follow the input format and constraints given in the original problem statement.
Output
Print the answer required by the problem.
Sample Input 1
3 1
Sample Output 1
1 2 3
Sample Input 2
4 2
Sample Output 2
1 2 1 3 1 4 2 3 2 4 3 4
Sample Input 3
4 4
Sample Output 3
1 2 3 4
Algorithm Classification
- Backtracking
Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static StringBuilder sb = new StringBuilder();
static int n, m;
static int[] arr;
public static void main(String[] args) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
StringTokenizer input = new StringTokenizer(br.readLine(), " ");
n = Integer.parseInt(input.nextToken());
m = Integer.parseInt(input.nextToken());
}
arr = new int[m];
dfs(0, 1);
System.out.println(sb);
}
/**
* Depth-first search (DFS)
*/
static void dfs(int depth, int start) {
if (depth == m) {
for (int value : arr) {
sb.append(value).append(" ");
}
sb.append("\n");
return;
}
for (int i = start; i <= n; i++) {
arr[depth] = i;
dfs(depth + 1, i + 1);
}
}
}