링크
https://www.acmicpc.net/problem/15649
자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.
첫째 줄에 자연수 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 8)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다.
수열은 사전 순으로 증가하는 순서로 출력해야 한다.
3 1
1
2
3
4 2
1 2
1 3
1 4
2 1
2 3
2 4
3 1
3 2
3 4
4 1
4 2
4 3
4 4
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1
scanf("%d %d", &N, &M);
DFS(0);
void DFS(int depth)
{
int i;
if (depth == M)
{
for (i = 0; i < M; i++)
printf("%d ", result[i]);
printf("\n");
}
else
{
for (i = 1; i <= N; i++)
{
if (check[i] == 0)
{
result[depth] = i;
check[i] = 1; //check[i]를 1로 함으로써 중복이 안되게 설정
DFS(depth + 1);
check[i] = 0;
}
}
}
}
#include <stdio.h>
int N, M;
int result[1000];
int check[1000]; //중복 체크
void DFS(int depth)
{
int i;
if (depth == M)
{
for (i = 0; i < M; i++)
printf("%d ", result[i]);
printf("\n");
}
else
{
for (i = 1; i <= N; i++)
{
if (check[i] == 0)
{
result[depth] = i;
check[i] = 1; //check[i]를 1로 함으로써 중복이 안되게 설정
DFS(depth + 1);
check[i] = 0;
}
}
}
}
int main(void)
{
scanf("%d %d", &N, &M);
DFS(0);
return 0;
}