Institute: Uie Department: Cse
Institute: Uie Department: Cse
DEPARTMENT : CSE
Bachelor of Engineering (Computer Science & Engineering)
Design and Analysis of Algorithms (CST-302)
2
Backtracking
• We can represent the solution space for the problem using a state space tree.
• Problem: Given n positive integers w1, ... wn and a positive integer S. Find all subsets of
w1, ... wn that sum to S.
• Example:
n=3, S=6, and w1=2, w2=4, w3=6
• Solutions:
{2,4} and {6}
Sum of Subsets
• The nodes at depth 1 are for including (yes, no) item 1, the nodes at depth 2 are for item 2, etc.
• The left branch includes wi, and the right branch excludes wi.
i1 2 0
yes no yes no
i2 6 2 4 0
i3 12 6 8 2 10 4 6 0
• Each node will save its depth and its (possibly partial) current solution.
• It does not check for every solution state (node) whether a solution has been
reached, or whether a partial solution can lead to a feasible solution
• Main idea: Backtracking consists of doing a DFS of the state space tree, checking whether
each node is promising and if the node is nonpromising backtracking to the node’s parent.
Backtracking
• The state space tree consisting of expanded nodes only is called the pruned
state space tree.
• The following slide shows the pruned state space tree for the sum of subsets
example.
0
3 0
3 0
4 0 4 0
7 3 4 0
5 0 5 0 5 0
12 7 8 3 9 4
6 0
13 7
if (promising ( v ))
if (aSolutionAt( v ))
write the solution
else //expand the node
for ( each child u of v )
checknode ( u )
Checknode
• Checknode uses the functions:
• Promising(v) which checks that the partial solution represented by v can lead
to the required solution.
3 7 12 4 0
8 3 15
5 0 5 0 5 0
13
4 12 5 7 9 8 10 3 9 14 4
6 0
6 13 7 7 - backtrack
Nodes numbered in “call” order
sumOfSubsets ( i, weightSoFar, totalPossibleLeft )
1) if (promising ( i )) //may lead
to solution
2)then if ( weightSoFar == S )
3) then print include[ 1 ] to include[ i ]
//found solution
4) else //expand the node when weightSoFar < S
5) include [ i + 1 ] = "yes” //try
including
6) sumOfSubsets ( i + 1,
weightSoFar + w[i + 1],
totalPossibleLeft - w[i + 1] )
n
19
REFERENCES
20
THANK YOU