## Thursday, December 27, 2012

### [LeetCode] 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`
» Solve this problem

[解题思路]

[Code]
``````1:      void nextPermutation(vector<int> &num) {
2:            // Start typing your C/C++ solution below
3:            // DO NOT write int main() function
4:            assert(num.size() >0);
5:            int vioIndex = num.size() -1;
6:            while(vioIndex >0)
7:            {
8:                 if(num[vioIndex-1] < num[vioIndex])
9:                      break;
10:                 vioIndex --;
11:            }
12:            if(vioIndex >0)
13:            {
14:                 vioIndex--;
15:                 int rightIndex = num.size()-1;
16:                 while(rightIndex >=0 && num[rightIndex] <= num[vioIndex])
17:                 {
18:                      rightIndex --;
19:                 }
20:                 int swap = num[vioIndex];
21:                 num[vioIndex] = num[rightIndex];
22:                 num[rightIndex] = swap;
23:                 vioIndex++;
24:            }
25:            int end= num.size()-1;
26:            while(end > vioIndex)
27:            {
28:                 int swap = num[vioIndex];
29:                 num[vioIndex] = num[end];
30:                 num[end] = swap;
31:                 end--;
32:                 vioIndex++;
33:            }
34:       }
``````

[已犯错误]
1. Line 16

while(rightIndex >=0 && num[rightIndex] < num[vioIndex])

JJ said...