next permutation
1 class Solution { 2 public: 3 void nextPermutation(vector<int> &num) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if( num.size() == 1 ) return; 7 int pos = -1; 8 for(int i = num.size() - 1; i>=1; i-- ) 9 if( num[i] > num[i-1] ) 10 { 11 pos = i-1; 12 break; 13 } 14 if( pos == -1 ) 15 { 16 sort(num.begin(),num.end() ); 17 return; 18 } 19 int top = INT_MAX; 20 int top_pos = -1; 21 for(int i = num.size() - 1; i>pos; i--) 22 { 23 if( num[i] > num[pos] && num[i] < top) 24 { 25 top_pos = i; 26 top = num[i]; 27 break; 28 } 29 } 30 31 num[top_pos] = num[pos]; 32 num[pos] = top; 33 sort(num.begin() + pos + 1, num.end() ); 34 return; 35 36 } 37 };
posted on 2013-09-04 19:16 jumping_grass 阅读(143) 评论(0) 收藏 举报
浙公网安备 33010602011771号