본문 바로가기
Java

[JAVA] next_permutation, prev_permutation

by onejunu 2020. 9. 19.
	static boolean nextPermutation(int[] arr){
        int i = arr.length-1;
        while(i>0 && arr[i-1]>=arr[i]) --i;

        if(i==0) return false;

        int j = arr.length - 1;
        while(arr[i-1]>=arr[j]) --j;

        int temp = arr[i-1];
        arr[i-1] = arr[j];
        arr[j] = temp;

        int k = arr.length-1;

        while(i<k){
            temp = arr[i];
            arr[i] = arr[k];
            arr[k] = temp;
            i++; k--;

        }
        return true;
    }
    static boolean prevPermutation(int[] arr)
    {
        int i = arr.length - 1;
        while (i > 0 && arr[i - 1] <= arr[i]) --i;

        if (i == 0) return false;

        int j = i - 1;
        while (j + 1 <= arr.length-1 && arr[j + 1] <= arr[i - 1]) ++j;

        int temp = arr[i-1];
        arr[i-1] = arr[j];
        arr[j] = temp;

        int k = arr.length-1;
        while(i<k){
            temp = arr[i];
            arr[i] = arr[k];
            arr[k] = temp;
            i++; k--;

        }
        return true;
    }

댓글