문제: https://www.acmicpc.net/problem/15649
15649번: N과 M (1)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해
www.acmicpc.net
백 트레킹 : https://namu.wiki/w/%EB%B0%B1%ED%8A%B8%EB%9E%98%ED%82%B9
코드:
package step_by_step.level15;
import java.util.Scanner;
public class N과M_1 {
static int[] arr;
static boolean[] visited;
static void asdf (int n, int m, int depth) {
if (depth == m) {
for (int val : arr) {
System.out.print(val + " ");
}
System.out.println();
return;
}
for (int i = 0; i < n; i++) {
if (!visited[i]) {
visited[i] = true;
arr[depth] = i + 1;
asdf(n, m, depth + 1);
visited[i] = false;
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
arr = new int[m];
visited = new boolean[n];
asdf(n, m, 0);
}
}
124가 출력된 후 13? 를 찾으로 되돌아가는 모습
728x90
반응형
'알고리즘' 카테고리의 다른 글
병합정렬, 힙정렬, 도수정렬 (0) | 2022.08.05 |
---|---|
shellSort 이해하기 (0) | 2022.07.18 |
하노이 탑이 이해가지 않는 나에게... (1) | 2022.06.21 |