Algorithm/백준
[백준] 15650번 N과 M (2)
sirius
2021. 3. 2. 11:22
https://www.acmicpc.net/problem/15650
15650번: N과 M (2)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해
www.acmicpc.net
중복을 방지하기 위해 start 변수를 두어 탐색 노드를 증가시킨다.
import java.util.*;
public class Main {
public static int N, M;
public static int[] arr;
public static boolean[] visit;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt(); // 자연수
M = sc.nextInt(); // 길이
arr = new int[M];
visit = new boolean[N];
dfs(0, 0);
}
private static void dfs(int start, int depth) {
if(M == depth) {
for(int num : arr) {
System.out.print(num + " ");
}
System.out.println("");
return;
}
for(int i = start ; i < N; i++) {
if(!visit[i]) {
visit[i] = true;
arr[depth] = i + 1;
dfs(i+1, depth+1);
visit[i] = false;
}
}
}
}