LeetCode31 Next Permutation and LeetCode60 Permutation Sequence

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

 

Subscribe to see which companies asked this question


 
该题在STL库里已经被实现,但是写下这种题目,有助于对模拟,还有边界条件的认识
以下是在LeetCode里提交后的排名
 只要能理清楚1234这个简单的排列的下一个排列1243和下下个排列1324是如何得到的,就可以列出以下三个关键点:
1.找出最后一个升序的位置,如果是最后两个数字,就直接交换最后两个数字
2.如果存在升序,但是不是最后两个数字,就交换升序位置的较小数字和后面数列里恰好比该数字大的数字(及比该数字大的最小数字);再将后面的数列按照从小到大的顺序排列
3.如果不存在升序的位置,就说明是一个轮回里的最后一个排列,下一个排列就是将数列反过来。
思考后发现第1点和第2点的程序是可以放在一起写
最后可以得到如下程序:
 
 
 本问题还有一种问法是60题 Permutation Sequence

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

 

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

 

Subscribe to see which companies asked this question


这就不能用上面的模拟操作来进行求解了,因为这样会超时(我试过,在n=9时超时)
所以要用数学规律来计算已知 n, k 条件下该输出什么
这里我们考虑一个数组1,2,3,4
如果固定第一个元素为1, 则后面的排列有3!个;如果固定第一个元素为2,则后面的排列有3!;同理可以依次考虑每一位固定后,后面的排列可能有多少种,这样就可以得到最终的排列,程序如下:
 
 
 





原文地址:https://www.cnblogs.com/gremount/p/5839461.html