首页 > 代码库 > leetcode. Next Permutation

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

采用字典排序法:

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