获得具有x个不同较小数字MATLAB的总数的不同组合



im基本上试图创建一个列表来表示可以给出"更改"(如金钱)的不同方式,我的例子是这个

 printCells(exchange([1,3,10],20))

并让输出

ans =
<0,0,2>
<1,3,1>
<2,6,0>
<4,2,1>
<5,5,0>
<7,1,1>
<8,4,0>
<10,0,1>
<11,3,0>
<14,2,0>
<17,1,0>
<20,0,0>

输出中的单元格表示每个指示符在该组合中使用的次数。 我试图对此使用递归,但我真的不知道从哪里开始

提前感谢,

好吧,我编写了一些递归,我得到了以下内容:

function [] = change()
    % specify inputs here
    options = [1,3,10];
    target  = 20;
    global solutions;   solutions = [zeros(1, size(options,2))];
    sum_up(options, target);
end
function [] = sum_up(options, target)
    clc;    
    recursive_sum(options, target, []);
end
function [] = recursive_sum(options, target, partial)
    global solutions;
    s = 0;
    for i=1:size(partial,2)
        s = s + partial(i);
    end
    if s == target
        entry = [];
        for i=1:size(options, 2)
            entry = [entry sum(partial == options(i))];
        end
        if ~sum(ismember(solutions(:,:), entry, 'rows'))
            fprintf('%d, ', entry);
            solutions = [solutions; entry];
            fprintf('= %dn', sum(partial));
        end
    end
    if s >= target
        return;
    end
    for i=1:size(options,2)
        recursive_sum(options, target, [partial options(i)]);
    end
end

带输出:

20, 0, 0, = 20
17, 1, 0, = 20
14, 2, 0, = 20
11, 3, 0, = 20
10, 0, 1, = 20
8, 4, 0, = 20
7, 1, 1, = 20
5, 5, 0, = 20
4, 2, 1, = 20
2, 6, 0, = 20
1, 3, 1, = 20
0, 0, 2, = 20

注意:您的 matlab .m 文件应该被称为 change.m

我希望我能帮助你:)

代码高尔夫

为了好玩,这里有一个非常小的版本:

function[]=change()
    o=[1,3,10]; t=20;
    global l; l=[zeros(1,size(o,2))];
    rs(o,t,[]); disp(l(2:end, :));
end
function[]=rs(o,t,p)
    global l; s=0;
    for i=1:size(p,2); s=s+p(i); end
    if s==t; e=[];
        for i=1:size(o, 2); e=[e sum(p==o(i))]; end
        if ~sum(ismember(l(:,:),e,'rows')); l=[l; e]; end
    end
    if s>=t; return; end
    for i=1:size(o,2); rs(o,t,[p o(i)]); end
end

最新更新