and example solution is log2 sub2 subsetSum1 8 5 2 4 log2

and example solution is

>> [log2, sub2] = subsetSum([1, 8, -5, -2], 4)

log2 =

1


sub2 =

1 8 -5

Inputs: (double) A 1 Times N vector (double) A single \"target\" number Outputs: (logical) Whether there is a subset of the vector that sums to the target number (double) The subset, if any, that sums to the target value Function Description: Given a vector and a \"target\", determine if there is a subset of the vector that sums to the target number. The first output should be a logical of whether or not such a subset exists and the second output should be the subset. If no such subset exists, the first output should be false and the second output should be the empty vector ([]). A target of 0 will always return true (selecting no elements sums to zero). Additionally, an empty vector as the first input will always return false (there are no elements to construct a sum out of).

Solution

Matlab Code

function ans = subsetSum(vec, target)

if target = = 0
ans = 1;
else if length(vec) = = 0 && target != 0

ans=0;

else if target = = vec(1)

ans=1;
else if subsetSum(vec(2:length(vec)), target)
ans = 1;
else if subsetSum(vec(2:length(vec)), target-vec(1))
ans=1;
else
ans = 0;
end

Thanks, Let me know if there is any concern.

and example solution is >> [log2, sub2] = subsetSum([1, 8, -5, -2], 4) log2 = 1 sub2 = 1 8 -5 Inputs: (double) A 1 Times N vector (double) A single \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site