n选m排列是一个经典算法题,如果m = n则称为全排列。
n选m排列问题的递归算法逻辑为:
1,将m个数的排列分为两部分:一部分为包含某个数k(1 <= k <= n)的m排列,一部分为不包含k的m排列;
2,对于包含k的排列,又可以分为两部分:一部分为包含某个数s(k < s <= n)的m-1排列,一部分为不包含s的m-1排列;
3,对于2步所得m-1排列,将k插入到每一个排列中的m个位置可以得到m个新的m排列;
4,同步骤2,对于不包含k的排列可以进行类似的操作,最终将得到所有的n个元素的m排列。
递归算法的伪代码:
Begin:
input m, n;
if m is bigger than n, then set m = n;
if m is smaller than or equal to 0, then return;
if n is smaller than or equal to 0, then return;
PartA: get m permutation contains 1;
PartB: get m permutation not contains 1;
collect two permutations;
End;
PartA:
input k, m, n;
if m is equal to 1, then return 1 permutation only k;
PartA: get m-1 permutation contains k+1;
if m is smaller than (n - k + 1), then:
PartB: get m-1 permutation not contains k+1;
collect two permutation sets in one set;
foreach m-1 permutati