Google+ Followers

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
要找的是右边第一个大于violate number的值,而不是等于。如果代码写成
while(rightIndex >=0 && num[rightIndex] < num[vioIndex]) 
那么在处理[1,5,1]时,会返回[1,1,5],而不是[5,1,1]

Post a Comment