Here is a high-level algorithm for SSUM.
for each subset T of S do {
if the elements of T sum to t then
return YES
}
return NO
The algorithm may have to check \(2^n\) possible solutions, so it takes at least an exponential amount of time to run.
Here is an implementation of the above high-level algorithm.
main {
S ← input array of positive integers
t ← input target number
n ← S.length
solution ← NO
check(1, 0)
return solution
}
check(i, sum) {
if i ≤ n then {
check(i+1, sum) /* don't include S[i] in the set */
check(i+1, sum + S[i]) /* include S[i] in the set */
} else if sum = t then {
solution ← YES
}
}
High-level algorithm.
/* algorithm sets min_dist to length of a shortest salesman tour */
main {
min_dist ← ∞
for each permutation π of the integers 2, ..., n do {
d ← length of the route starting at city 1
visiting cities 2, ..., n in the order given by π,
and returning to city 1;
min_dist ← min{min_dist, d}
}
return min_dist
}
The low-level algorithm in the next slide shows that this high-level algorithm can be implemented so that the running time is \(O(n!)\).
We use \(\pi[1..n]\) to keep the permutations.
main {
min_dist ← ∞
for j ← 1 to n do
π[j] ← j
perm(2)
return min_dist
}
perm(i) {
if i = n then {
d ← dist[π[n], 1]
for j ← 1 to n-1 do
d ← d + dist[π[j], π[j+1]]
if d < min_dist then
min_dist ← d
} else {
for j ← i to n do {
swap(π[i], π[j])
perm(i+1)
swap(π[i], π[j])
}
}
}