Tuesday, March 26, 2013

Next Permutation


/*

Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

*/
class Solution {
public:
    void swap(vector<int> &num, int i, int j){
        int temp = num[i];
        num[i] = num[j];
        num[j] = temp;
    }
    int partition(vector<int> &num, int i, int j){
        int smallIndex = i;;
        int pivot =  num[i];
       
        int k;
        for(k=i+1; k<=j; k++){
            if(num[k]<pivot){
                smallIndex++;
                swap(num, smallIndex, k);
            }
        }
       
        swap(num, i, smallIndex);
       
        return smallIndex;
    }
    void sort(vector<int> &num, int i, int j){
        int k;
        if(i<j){
            k = partition(num, i, j);
            sort(num, i, k-1);
            sort(num, k+1, j);
        }  
    }
    void nextPermutation(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int size = num.size();
        if(size<=1) return;
       
        int i;
        int j;
        for(i=size-2; i>=0; i--){
            for(j=size-1; j>i; j--){
                if(num[i]<num[j]){
                    swap(num, i, j);
                    sort(num, i+1, size-1);
                    return;
                }
               
            }
        }
       
        int mid = size/2 - 1;
        for(i=0; i<=mid; i++){
            swap(num, i, size-1-i);
        }
    }
};

No comments:

Post a Comment