Matlab求元素集合的排列组合

主要用到了递归的思想,例如,1 2 3 4的排列可以分为1 [2 3 4]、2 [ 1 3 4]、3 [ 1 2 4]、4 [1 2 3]进行排列,然后对括号里的数据进行类似排序([2 3 4]:2 [ 3 4]、3 [2 4]、4 [2 3])。

  • 代码
function perm(num_list, st, en)
% num_list:数据集合;
% st:起始位置
% en:终点位置
if st == en
    disp(num2str(num_list));  % 当起点和终点重合时,输出一个组合
else
    for i = st : en
        % 交换起点和i位置的元素
        t = num_list(st);
        num_list(st) = num_list(i);
        num_list(i) = t;
        % 起点位置+1,重复过程
        perm(num_list, st + 1, en)
        % 将数据集合还原到初始状态
        t = num_list(st);
        num_list(st) = num_list(i);
        num_list(i) = t;
    end
end
  • 测试
perm([1 2 3 5], 1, 4)  % 对所有元素
1  2  3  5
1  2  5  3
1  3  2  5
1  3  5  2
1  5  3  2
1  5  2  3
2  1  3  5
2  1  5  3
2  3  1  5
2  3  5  1
2  5  3  1
2  5  1  3
3  2  1  5
3  2  5  1
3  1  2  5
3  1  5  2
3  5  1  2
3  5  2  1
5  2  3  1
5  2  1  3
5  3  2  1
5  3  1  2
5  1  3  2
5  1  2  3

perm([1 2 3 5], 1, 3)  % 对前3个元素
1  2  3  5
1  3  2  5
2  1  3  5
2  3  1  5
3  2  1  5
3  1  2  5

perm([1 2 3 5], 2, 4)  % 对后3个元素
1  2  3  5
1  2  5  3
1  3  2  5
1  3  5  2
1  5  3  2
1  5  2  3

猜你喜欢

转载自blog.csdn.net/u012366767/article/details/81631806