Skip to content

Instantly share code, notes, and snippets.

@henryyang42
Created May 21, 2017 18:14
Show Gist options
  • Select an option

  • Save henryyang42/5d3d50c18df95e475fa732b7d7563efb to your computer and use it in GitHub Desktop.

Select an option

Save henryyang42/5d3d50c18df95e475fa732b7d7563efb to your computer and use it in GitHub Desktop.
function x = subset_sum(M,Sum)
[~, n] = size(M);
S = {0};
C = [0];
for i=1:n
[~, sz] = size(S);
ai = 1;
for j = 1:sz
arr = S{j};
if arr(1) + M(i) <= Sum && ~any(ismember(C, arr(1) + M(i)))
arr(1) = arr(1) + M(i);
S{sz+ai} = [arr M(i)];
ai = ai + 1;
C = [C arr(1)];
end
end
end
[~, sz] = size(S);
for i = 1:sz
if S{i}(1) == Sum
x = S{i}(2:end);
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment