
1부터 N까지의 범위의 반복문을 N 만큼 돌면 모든 순열을 구할 수 있다.
반복문을 N 만큼 돌고 싶다면 재귀 함수를 활용해 주면 된다.
#include <iostream>
#include <vector>
using namespace std;
bool isUsed[9];
int N, arr[8];
void dfs(int depth)
{
if (depth == N) // 모두 탐색한 경우
{
for (int i = 0; i < N; ++i)
{
cout << arr[i] << " ";
}
cout << "\n";
return;
}
for (int i = 1; i <= N; ++i)
{
if (isUsed[i]) // 이미 사용한 수
{
continue;
}
arr[depth] = i;
isUsed[i] = true;
dfs(depth + 1);
isUsed[i] = false;
}
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0);
cin >> N;
dfs(0);
return 0;
}
이미 사용한 수는 체크해 주면서 사용하지 않은 수를 골라서 다음 재귀 함수로 넘어가면 된다.
반복문이 1부터 시작하기에 자동으로 사전순을 보장해 준다.