码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode. Next Permutation

时间:2014-11-16 12:00:58      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   for   div   

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

采用字典排序法:

1) 找到最大的k, 使得a[k] < a[k + 1], 此时a[k + 1], ..., a[n - 1]为非增序
2) 对a[k + 1], ..., a[n - 1], 找到j, 使得j = min{a[i] > a[k] | i > k && i < n}, 交换a[k], a[j]
3) a[k + 1], ..., a[n - 1]从小到大排序, 因为已经是非增序,直接首位连续交换即可.

 1 void nextPermutation(vector<int> &num) 
 2     {
 3         int i, k = 0, j = 0, min = 0x7fffffff;
 4         
 5         for (i = 0; i < num.size() - 1; i++)
 6         {
 7             if (num[i] < num[i + 1])
 8                 k = i;
 9         }
10         
11         for (i = k + 1; i < num.size(); i++)
12         {
13             if ((num[i] > num[k]) && (num[i] <= min))   /* 最后形成降序 */
14             {
15                 min = num[i];
16                 j = i;
17             }
18         }
19         
20         swap(num[k], num[j]);
21         if (0 == (k + j))
22             k = -1;
23         for (i = k + 1, j = num.size() - 1; i < j; i++, j--)
24             swap(num[i], num[j]);
25     }

 

leetcode. Next Permutation

标签:style   blog   io   color   ar   os   sp   for   div   

原文地址:http://www.cnblogs.com/ym65536/p/4101174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!