10974번: 모든 순열
N이 주어졌을 때, 1부터 N까지의 수로 이루어진 순열을 사전순으로 출력하는 프로그램을 작성하시오.
www.acmicpc.net
import java.util.Scanner;
class Main {
static int N;
static int[] arr;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
arr = new int[N];
int number = 1;
for(int i=0; i<N; i++) {
arr[i] = number++;
}
perm(0);
}
public static void perm(int depth) {
if(depth == N) {
for(int i=0; i<N; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
for(int i=depth; i<N; i++) {
rightRotate(depth, i);
perm(depth+1);
leftRotate(depth, i);
}
}
public static void rightRotate(int s, int e) {
int temp = arr[e];
for(int i=e; i>s; i--) {
arr[i] = arr[i-1];
}
arr[s] = temp;
}
public static void leftRotate(int s, int e) {
int temp = arr[s];
for(int i=s; i<e; i++) {
arr[i] = arr[i+1];
}
arr[e] = temp;
}
}
'ALGORITHM > 프로그래머스 | 백준 | 삼성 | 카카오' 카테고리의 다른 글
[SWEA] 6782. 현주가 좋아하는 제곱근 놀이 (0) | 2020.05.17 |
---|---|
[SWEA] 5215. 햄버거 다이어트 (0) | 2020.05.17 |
[프로그래머스] 쇠막대기 (0) | 2020.05.11 |
[프로그래머스] 프린터 (0) | 2020.05.05 |
[프로그래머스] 주식가격 (0) | 2020.05.04 |