【LeetCode】 Permutations 排列生成算法之字典序法

字典序排序生成算法

字典序法就是按照字典排序的思想逐一产生所有排列。

例如,由1,2,3,4组成的所有排列,从小到大的依次为:

1234, 1243, 1324, 1342, 1423, 1432,2134, 2143, 2314, 2341, 2413, 2431,3124, 3142, 3214, 3241, 3412, 3421,4123, 4132, 4213, 4231, 4312, 4321.

分析这种过程,看后一个排列与前一个排列之间有什么关系?

再如,,设有排列(p)=2763541,按照字典式排序,它的下一个排列是什么?

2763541 (找最后一个正序35)2763541 (找3后面比3大的最后一个数4)2764531 (交换3,4的位置)2764135(把4后面的5,3,1反转)

下面给出求 p[1…n] 的下一个排列的描述:

求 i = max{j | p[j – 1] < p[j]} (找最后一个正序)求 j = max{k| p[i – 1] < p[k]} (找最后大于 p[i – 1] 的)交换 p[i – 1] 与 p[j]得到 p[1] … p[i-2]p[j]p[i] p[i+1] … p[j-1]p[i-1]p[j+1] … p[n]反转 p[j] 后面的数得到 p[1] … p[i-2]p[j] p[n] … p[j+1] p[i-1] p[j-1] … p[i]Next Permutation

Description:

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,23,2,1 → 1,2,31,1,5 → 1,5,1

题意:实现一个求下一个排列的方法。要求:1) 下一个排列要在字典序上大于当前排列;2) 如果没有比当前序列更大的排列,那么下一个为最小的排列;3) 需要在原地操作,即不用额外的空间。

分析:按照上面的方法直接实现即可。需要注意与上面方法不同的是,下面的实现是循环的,即字典序的最后一个排列[4,3,2,1]的后面是[1,2,3,4]。

Permutations

Description:Given a collection of numbers, return all possible permutations. For example, [1,2,3] have the following permutations: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

题意:求集合中所有数的全排列。

分析:我们知道n个数的全排列有n!个,那么根据Next Permutation一个一个求出即可。

Permutations II

Description:Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1].

题意:求集合中所有数的全排列,注意集合中可能存在重复的数。

分析:方法与Permutations相同,只是有了重复数后,全排列的总数就不足n!个了,我们的方法是先对所有数排序,即从最小的排列开始找,找到最后一个排列时结束。

Permutation Sequence

Description: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.

题意:按照字典序法,求n个数的全排列中第k个排列,注意返回排列的形式为字符串。

分析:从最小的排列开始,根据Next Permutation找到第k个排列即可。

(完)

转载请注明:来自梁佳宾的网络日志

文章原地址:[LeetCode] Permutations 排列生成算法之字典序法

最糟糕的行为是抱怨,最易见效 的努力是从自己做起。

【LeetCode】 Permutations 排列生成算法之字典序法

相关文章:

你感兴趣的文章:

标签云: