generating all permutations of the numbers 1, 2, . . . , n.
1[all the permutations of the numbers 2,3,…,n],
2[all the permutations of the numbers 1,3,…,n],
……,
n[all the permutations of the numbers 1,2,…,n-1]
![](https://i-blog.csdnimg.cn/blog_migrate/50f18192e24542bf0424ffcb3c0a531d.png)
- 首先,我们创建一个数组P[],用来存储排列结果。数组P的长度为n,表示排列中包含的数字范围从1到n。
- 我们从1到n的循环,将数组P[]初始化为1到n的有序排列。
- 接着,调用perml(1)这个过程,开始生成排列。
- 过程perml(m)的目标是生成从m到n的所有排列。
- 如果m等于n,表示我们已经完成了整个排列,将当前的排列输出。
- 否则,我们从m到n的循环,每次交换P[m]和P[j]的值,然后递归调用perml(m+1),直到达到最后一个数字n。
- 当递归回溯到上一层时,再次交换P[m]和P[j]的值,以确保在下一轮迭代中能够重新考虑所有可能的排列。
- 最终,当m等于n时,输出P[1..n]表示一种排列
Since there are n! permutations, Step 1 of Procedure perm1 takes nn! to output all permutations.
Now we count the number of iterations of the for loop. In the first call to Procedure perm1, m = 1. Hence, the for loop is executed n times plus the number of times it is executed in the recursive call perm1(2). When n = 1, the number of iterations is zero, and the number of iterations f(n) can be expressed by the recurrence
n [x x…x x] ,
[´] n [x … x x],
……,
[ x x … x x] n.
First, we put n in P[1] and generate all the permutations of the first n − 1 numbers using the subarray P[2..n]. Next, we put n in P[2] and generate all the permutations of the first n − 1 numbers using the subarrays P[1] and P[3..n]. Then, we put n in P[3] and generate all the permutations of the first n−1 numbers using the subarrays P[1..2] and P[4..n]. This continues until finally we put n in P[n] and generate all the permutations of the first n − 1 numbers using the subarray P[1..n − 1]. Initially, all n entries of P[1..n] contain 0’s.
- 首先,我们创建一个数组P[],用来存储排列结果。数组P的长度为n,表示排列中包含的数字范围从1到n。
- 我们从1到n的循环,将数组P[]初始化为0。
- 接着,调用perm2(n)这个过程,开始生成排列。
- 过程perm2(m)的目标是生成从m到0的所有排列。
- 如果m等于0,表示我们已经完成了整个排列,将当前的排列输出。
- 否则,我们从1到n的循环,对于每个位置j,如果P[j]等于0,表示该位置还没有被填入数字,则我们将数字m填入该位置。
- 然后,递归调用perm2(m-1),继续填入下一个数字。
- 在递归返回之前,将填入的数字重新置为0,以便下一轮迭代使用。
- 当所有位置都填满数字后,输出当前排列。
- 最终,当m等于0时,输出P[1..n]表示一种排列。
Since there are n! permutations, Step 1 of Procedure perm2 takes nn! to output all permutations.
Now we count the number of iterations of the for loop. The for loop is executed n times in every call perm2(m) plus the number of times it is executed in the recursive call perm2(m − 1). When Procedure perm2 is invoked by the call perm2(m) with m > 0, the array P contains exactly m zeros, and hence the recursive call perm2(m − 1) will be executed exactly m times. When m = 0, the number of iterations is zero, and the number of iterations can be expressed by the recurrence