首页 > 技术文章 > [leetcode]Next Permutation

aituming 2015-01-27 22:17 原文

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. 从后往前遍历, 找到第一个比前一个数字小的数,记录下其下标;

2. 再从后往前遍历,找个第一个比步骤1找到的数大的数;

3. 交换步骤1,2找到的数;

4. 将步骤1下标指代的数后面的序列逆置。

 

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 void nextPermutation(vector<int> &num) 
 7 {
 8     int len = num.size();
 9     if (len<=1)
10         return;
11     int i=len-2;
12     for( ;len>=0; i--)
13         if(num[i]<num[i+1])
14             break;
15     if(i<0)
16     {
17         reverse(num.begin(), num.end());
18         return;
19     }
20 
21     int j=len-1;
22     for( ;len>=0; j--)
23         if(num[j]>num[i])
24             break;
25     
26 swap(num[i], num[j]); 27 reverse(num.begin()+i+1, num.end()); 28 } 29 30 int main() 31 { 32 int a[]={1, 2, 3}; 33 vector<int> ivec(a, a+3); 34 nextPermutation(ivec); 35 }

 

扩展:

康托编码:

X=a[n]*(n-1)!+a[n-1]*(n-2)!+...+a[i]*(i-1)!+...+a[1]*0! 其中,a[i]为整数,并且X=a[n]*(n-1)!+a[n-1]*(n-2)!+...+a[i]*(i-1)!+...+a[1]*0!。这就是康托展开。

用这个公式可以求某个排列是这些数字构成的所有排列从小到大排列所在的位置。

{1,2,3,4,...,n}表示1,2,3,...,n的排列如 {1,2,3} 按从小到大排列一共6个。123 132 213 231 312 321 。
代表的数字 1 2 3 4 5 6 也就是把10进制数与一个排列对应起来。
他们间的对应关系可由康托展开来找到。
如我想知道321是{1,2,3}中第几个小的数可以这样考虑 :
第一位是3,当第一位的数小于3时,那排列数小于321 如 123、 213 ,小于3的数有1、2 。所以有2*2!个。再看小于第二位2的:小于2的数只有一个就是1 ,所以有1*1!=1 所以小于321的{1,2,3}排列数有2*2!+1*1!=5个。所以321是第6个小的数。 2*2!+1*1!+0*0!就是康托展开。
 
 1 const int PermSize=12;
 2 long long factory[PermSize]={0,1,2,6,24,120,720,5040,40320,362880,3628800,39916800};
 3 long long Cantor(string buf)
 4 {
 5     int i,j,counted;
 6     long long result=0;
 7     for(i=0;i<PermSize;++i)
 8     {
 9         counted=0;
10         for(j=i+1;j<PermSize;++j)
11             if(buf[i]>buf[j])
12                 ++counted;
13         result=result+counted*factory[PermSize-i-1];
14     }
15     return result;
16 }

 

推荐阅读