ALGORITHM/프로그래머스 | 백준 | 삼성 | 카카오

[백준] 10974번 모든 순열

SZCODE 2020. 5. 17. 22:56

www.acmicpc.net/problem/10974

 

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;
   }
}