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

C++:
01 bool compare(int i, int j)
02 {
03     return i<j;
04 }
05 void swap(int i, int j, vector<int> &num)
06 {
07     int t=num[i];
08     num[i]=num[j];
09     num[j]=t;
10 }
11 class Solution {
12 public:
13     void nextPermutation(vector<int> &num) {
14         // Start typing your C/C++ solution below
15         // DO NOT write int main() function
16         int n=num.size();
17         bool flag=false;
18         if(n<=1)
19             return;
20         int i=n2;
21         for(;i>=0;i)
22         {
23             if(num[i]<num[i+1])
24             {
25                int j=i+1;
26                while(j<n)
27                {
28                    if(num[i]>=num[j])
29                    {
30                        swap(i,j1,num);
31                        flag=true;
32                        break;
33                    }
34                    j++;
35                }
36                if(flag==false)
37                 swap(i,j1,num);
38                break;
39             }
40         }
41         sort(num.begin()+i+1,num.end(),compare);
42     }
43 };
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s