对行值的所有排列求和



我在MATLAB中有一个问题,我认为这可以很好地解决使用例如递归。我只是想知道是否有一个更优雅的(可能是矢量化的)解决方案,利用一些内置函数。

问题来了:

给定是一个(n × 2)-矩阵。找出所有可能的和,其中每一行恰好有一个值。

示例1:

A = [a b; 
     c d]; % I use variable names/symbolic values to make it clearar

结果2:

result = [a+c; a+d; b+c; b+d];

示例2:

A = [a b;
     c d;
     e f];
result = [a+c+e; a+c+f; a+d+e; a+d+f; b+c+e; b+c+f; b+d+e; b+d+f];

我希望我的问题是清楚的:)由于

[m n] = size(A);
cols = dec2base(0:n^m-1,n)+1 - '0'; %// all combinations of cols
ind = bsxfun(@plus, 1:m, (cols-1)*m).'; %'// convert into linear index
result = sum(A(ind));

是的,递归是一个好方法。

每个这样的n行矩阵的和集合可以通过首先计算其前n-1行的和集合,然后将左下角或右下角的数字添加到该集合中的每个数字中来找到。在伪代码:

sumset(M):
    If nrows(M) = 1 then return { M[1, 1], M[1, 2] }.
    S = sumset(first nrows(M)-1 rows of M)
    X = { }
    For each number s in S:
        Insert M[nrows(M), 1] + s into X.
        Insert M[nrows(M), 2] + s into X.
    Return X.

这将产生2^n个数字。

最新更新