题目
来源于Mathwork上的Cody,Problem 660 - Find a subset that divides the vector into equal halves.
Given a vector x, return the indices to elements that will sum to exactly half of the sum of all elements.
Example:
Input x = [1 2 3 4 5 6 7]
Output xi = [1 6 7]
because
sum(x) = 28
sum(x([1 6 7])) = 14
The answer is not necessarily unique and the order is unimportant. We will just test to make sure that sum(x)/2 is sum(x(xi))
代码
function xi = split_it(x)
xi = [];
v=1:length(x);
x_ban=sum(x)/2;
for i=1:length(x)
C = nchoosek(v,i);
for j=1:size(C,1)
if sum(x(C(j,:)))==x_ban
xi = [xi;C(j,:)];
break;
end
end
if ~isempty(xi)
break;
end
end
end