Willing is not enough, we must doBruce lee
Problem Statement:In the subset-sum problem, we are given a finite set S of positive integers and an integer target t > 0. We ask whether there exists a subset S` S ⊆ whose elements sum to t.
TRUE FALSE
t = 138457 TRUE
How to Design an Algorithm to Solve this Problem??
Brute Force??Making all possible Subsets
A={1,2,4}
What will be its Complexity???All possible subsets???1. A’={}2. A’={1}3. A’={1,2}4. A’={1,4}5. A’={1,2,4}6. A’={2}7. A’={2,4}8. A’={4}
SumOFSubset=2n=8
Brute Force Subset Sum Solution
Running time Î Q(n 2n )What does this tell us about the timecomplexity of the subset sum problem?
bool SumSub (w, i, j){
if (i == 0) return (j == 0);else
if (SumSub (w, i-1, j)) return true;
else if ((j - wi) >= 0) return SumSub (w, i-1, j - wi);
else return false;}
Complexity0( 2n N)
All possible subsets and time required to sum them.
Brute Force??? No, thanks
Why is this Failing???
• Sometimes, the divide and conquer approach seems appropriate but fails to produce an efficient algorithm.
• One of the reasons is that D&Q produces overlapping sub problems.
Reason
Dynamic ApproachDivide and conquer with Tabular form
Solves a sub-problem by making use of previously stored solutions for all other sub problems.
HOW?????
Lets take an example
0 1 2 3 4 5 6 7 8 9 10 11
2
3
7
8
10
A={2,3,7,8,10} t=11
Any subset of { 2} making sum=0 ???
Lets take an example
0 1 2 3 4 5 6 7 8 9 10 11
2 T
3
7
8
10
A={2,3,7,8,10} t=11
Lets take an example
0 1 2 3 4 5 6 7 8 9 10 11
2 T F
3
7
8
10
A={2,3,7,8,10} t=11
Any subset of { 2} making sum=1 ???
Lets take an example
0 1 2 3 4 5 6 7 8 9 10 11
2 T F T
3
7
8
10
A={2,3,7,8,10} t=11
Any subset of { 2} making sum=3 ???
Lets take an example
0 1 2 3 4 5 6 7 8 9 10 11
2 T F T F F F F F F F F F
3 T F T T F T F F F F F F
7 T F T T F T F T F T T F
8 T F T T F T F T T T T T
10 T F T T F T F T T T T T
A={2,3,7,8,10} t=11
How to get the Answer??
8 is one of the Element
3 is one of the Element
As we have reached the Last row..A’={8,3} is our Answer
18
Dynamic Programming Algorithmbool SumSub (w , n , m){1. t[0,0] = true; for (j = 1 to m) t[0,j] = false;2. for (i = 1 to n)3. for (j = 0 to m)4. t[i,j] = t[i-1,j];
5. if ((j-wi) >= 0)
6. t[i,j] = t[i-1,j] || t[i-1, j – wi];7. return t[n,m];}
i-1,j - wi
i-1,j
i , j
Its Complexity???Time complexity is T(n) = O(m) + O(nm) = O(nm)
ApplicationTraveling Salesperson Problem–Input: a graph of cities and roadswith distance connecting them and aminimum total distant–Output: either a path that visits eachwith a cost less than the minimum,or “no”.• If given a path, easy to check if itvisits every city with less thanminimum distance travelled.
Drug Discovery Problem–Input: a set ofproteins, a desired3D shape–Output: a sequenceof proteins thatproduces the shape(or impossible)If given a sequence, easy tocheck if sequence has the right shape.
THE END