【问题标题】:Summing up all permutations of row values总结行值的所有排列
【发布时间】:2014-06-04 09:01:28
【问题描述】:

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

那么问题来了:

给定一个 (n x 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];

我希望我的问题很清楚 :) 谢谢

【问题讨论】:

标签: arrays algorithm matlab matrix


【解决方案1】:
[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));

【讨论】:

    【解决方案2】:

    是的,递归是个好方法。

    可以通过首先计算其前 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 个数字。

    【讨论】:

      猜你喜欢
      • 2021-01-21
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多