返回其他整数之和的整数集(向量)的函数

时间:2014-04-28 13:48:48

标签: matlab knapsack-problem

我正在寻找一个Matlab函数,它帮助我设置一个整数向量,乘以其他已知向量将是另一个已知整数的总和。

例如:

V = [1, 2, 3, 4]
X = 10
results =
[10, 0, 0, 0] 
[8, 1, 0, 0]
.....
[0, 2, 0, 2]
etc.

我正在尝试解决类似于离散背包问题的问题。

1 个答案:

答案 0 :(得分:1)

你总是可以使用暴力(可能会有更有效的方法):

%// Data
V = [1 2 3 4];
X = 10;

%// Generate all combinations of n integers from 0 to X
%// (same approach as in http://stackoverflow.com/q/21895335/2586922 )
n = numel(V);
c = cell(1,n);
[c{:}] = ndgrid(0:X);
c = cat(n+1,c{:});
c = reshape(c,[],n);

%// Test which combinations are valid, and keep only those
s = sum(bsxfun(@times, c, V),2);
result = c(s==X,:);

在您的示例中,有23种有效组合:

result = 
    10     0     0     0
     8     1     0     0
     6     2     0     0
     4     3     0     0
     2     4     0     0
     0     5     0     0
     7     0     1     0
     5     1     1     0
     3     2     1     0
     1     3     1     0
     4     0     2     0
     2     1     2     0
     0     2     2     0
     1     0     3     0
     6     0     0     1
     4     1     0     1
     2     2     0     1
     0     3     0     1
     3     0     1     1
     1     1     1     1
     0     0     2     1
     2     0     0     2
     0     1     0     2