이전 순열
09 Mar 2020 | Algorithm
import java.util.Scanner;
import java.util.Stack;
public class BOJ_10973 {
static int[] arr;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
prevPermutation();
}
private static void prevPermutation() {
int idx = arr.length - 1;
while (true) {
if (idx == 0) {
System.out.println(-1);
break;
}
if (arr[idx - 1] < arr[idx]) {
idx -= 1;
continue;
}
int i = idx;
int j = -1;
for (int k = i - 1; k < arr.length; k++) {
if (arr[i - 1] > arr[k]) {
j = k;
}
}
if (j != -1) {
swap(i - 1, j);
reverse(i);
print();
break;
}
}
}
private static void print() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]);
if (i != arr.length - 1)
sb.append(" ");
}
System.out.println(sb.toString());
}
private static void reverse(int i) {
Stack<Integer> stack = new Stack<>();
for (int j = i; j < arr.length; j++) {
stack.add(arr[j]);
}
for (int j = i; j < arr.length; j++) {
arr[j] = stack.pop();
}
}
private static void swap(int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}