티스토리 뷰

Algorithms/BOJ

Q10972 다음순열

PeonyF 2020. 3. 6. 15:33
반응형

 

 

 

기본값 이후의 배열을 비내림차순으로 만든 후 출력(순열)

가장 끝에서 부터 비교하는 이유: 처음 시작하는 순열의 최소값이여야 하므로

723/6541   3보다 큰수 : 6,5,4 중 가장 끝에 있는 수 선택 => 724/6531(O)

                                                                         => 726/5431 (X)

 

import java.util.Scanner;

public class Q10972 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int countNum = sc.nextInt();
        int[] permutationList = new int[countNum];

        for (int i = 0; i < countNum; i++) {
            permutationList[i] = sc.nextInt();
        }

        NextPermutation nextPermutation = new NextPermutation(permutationList);
        nextPermutation.printPermutation();


    }
}

class NextPermutation {
    private int[] permutationList;
    private int size;

    NextPermutation(int[] permutationList) {
        this.permutationList = permutationList;
        size = permutationList.length;

    }

    void printPermutation() {
        if (flagNextPermutation()) {
            for (int element : permutationList) {
                System.out.print(element + " ");
            }
        } else {
            System.out.println("-1");
        }

    }

    private boolean flagNextPermutation() {
    
     //1. a[i-1] < a[i] 를 만족하는 i를 찾는다.
     
        int i = size - 1;
        while (i > 0 && permutationList[i - 1] >= permutationList[i]) {
            i -= 1;
        }

        if (i <= 0) {
            return false;
        }
        
       //2.다시 j부터 j>=I 를 만족, a[j] > a[i-1]를 만족하는 첫번째 수
       
        int j = size - 1;
        while (permutationList[j] <= permutationList[i - 1]) {
            j -= 1;
        }
        
        //3. swap

        swap(i - 1, j);
        
        //4. 순열뒤집기

        j = size - 1;
        while (i < j) {
            swap(i, j);
            i++;
            j--;
        }
        return true;

    }

    private void swap(int i, int j) {
        int temp = permutationList[i];
        permutationList[i] = permutationList[j];
        permutationList[j] = temp;
    }


}


 

* 참고자료 : https://dundung.tistory.com/58

 

백준 10972 이전 순열 & 10973 다음 순열 Java

순열은 순서가 부여된 임의의 집합을 다른 순서로 뒤섞는 연산이다. N=3 인경우에 사전순으로 나열하면 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 이 된다. 크기가 N인 순열의 개수는 총 N!이다. (N팩토리얼) 1 2 3의..

dundung.tistory.com

 

반응형

'Algorithms > BOJ' 카테고리의 다른 글

백준 17298  (0) 2023.01.11
백준 Q.1157 단어 공부  (0) 2020.01.08
백준 Q.1159 농구 경기  (0) 2020.01.08
백준 Q.1302 베스트셀러  (0) 2020.01.07
백준 Q.9375 패션왕 신해빈  (0) 2020.01.06
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함