6 Backtracking

Design and Analysis of Algorithms ยท Unit 6 ยท 5 hrs

Backtracking

Exam-focused notes for Backtracking (Design and Analysis of Algorithms, CSC325): what the TU syllabus asks and how it has actually been tested, with 9 solved past questions from this unit.

Backtracking in short

Backtracking systematically searches through every possible way of building a solution, abandoning ("backtracking out of") a partial solution the moment it can be proven not to lead anywhere valid, rather than continuing to extend it uselessly. This unit sets out the technique in general and then applies it to three classic combinatorial search problems.

Backtracking: notes

Concept of Backtracking, Recursion vs Backtracking

Backtracking builds a solution incrementally, one decision at a time, viewing the space of all partial solutions as an implicit tree: the root is the empty choice, and each node's children are the ways of extending it by one more decision. At each node a feasibility check decides whether the partial solution can still possibly be completed into a valid one; if not, the whole subtree rooted there is skipped (pruned) without being explored, and the search backtracks to the parent to try the next untried choice. This makes backtracking a depth-first search of the state-space tree with pruning, which is why it can solve problems whose naive search space is exponential while, in practice, exploring only a small fraction of it.

Recursion and backtracking are closely related but not identical. Recursion breaks a problem into smaller instances of the same problem and combines their solutions, typically following a single predetermined path down to the base case, as in computing a factorial or a GCD. Backtracking explores multiple candidate choices at each step, using recursion as its mechanism, but it can abandon a branch and retry a different choice at the same level, something plain recursive functions such as factorial never need to do. Backtracking is well suited to problems phrased as "find (all) arrangements/subsets/assignments satisfying constraints", such as N-Queens, Sudoku, subset selection, and graph colouring, whereas plain recursion is used when a single, uniquely determined decomposition solves the problem.

What this unit covers

  • Concept of Backtracking, Recursion vs Backtracking
  • Backtracking Algorithms: Subset-sum Problem, Zero-one Knapsack Problem, N-queen Problem and their Analysis

Backtracking Algorithms

2082 ยท 5 marks

Find all possible subsets of the integers that sum to 21 in the array {5, 6, 10, 11, 15} using back tracking technique. [5]

Show solved answer

Subset Sum Using Backtracking

Given

  • Set of integers: $W = {5, 6, 10, 11, 15}$ (already in ascending order)
  • Number of elements: $n = 5$
  • Target sum: $M = 21$

Goal: find all subsets whose elements sum to exactly $21$.


Solution

Method

For the sum-of-subsets backtracking algorithm, keep track of:

  • $s$ = sum of elements included so far
  • $r$ = sum of remaining elements not yet considered

Total sum $= 5+6+10+11+15 = 47$.

Bounding (pruning) conditions at element $w_k$:

  1. Prune if $s + w_k > M$ (including this element overshoots the target).
  2. Prune if $s + r < M$ (even including everything left cannot reach the target).

Manual enumeration of valid subsets

Since the total is only 47 and target 21, I enumerate feasible include/exclude branches.

Branch: include 5 (s=5)

  • include 6 (s=11): include 10 โ†’ $s=21$ โœ… {5,6,10}
    • exclude 10 (r left = 11+15=26, s+r=37 ok): +11 โ†’ 22 > 21 prune; exclude 11: +15 โ†’ 26 > 21 prune. No solution.
  • exclude 6 (s=5): include 10 (s=15): +11โ†’26 prune; exclude 11: +15โ†’30 prune. No solution.
    • exclude 10 (s=5): +11โ†’16, then +15โ†’31 prune, exclude 15โ†’16 no; exclude 11 (s=5): +15โ†’20 no. No solution.

Branch: exclude 5 (s=0)

  • include 6 (s=6): include 10 (s=16): +11โ†’27 prune; +15โ†’31 prune. No solution.
    • exclude 10 (s=6): +11โ†’17 then +15โ†’32 prune, excludeโ†’17 no; exclude 11 (s=6): +15 โ†’ $21$ โœ… {6,15}
  • exclude 6 (s=0): include 10 (s=10): +11 โ†’ $21$ โœ… {10,11}
    • exclude 11 (s=10): +15โ†’25 prune. No solution.
    • exclude 10 (s=0): +11โ†’11 then +15โ†’26 prune; +15 aloneโ†’15 no. No solution.

Verification of each solution

$$5+6+10 = 21 \checkmark \qquad 6+15 = 21 \checkmark \qquad 10+11 = 21 \checkmark$$

(Check no others: any subset with 15 needs 6 more โ†’ only {6}; any with 11 needs 10 more โ†’ only {10}; without 11 and 15, max useful combos {5,6,10}=21. Confirmed complete.)


Final Answer: All Subsets Summing to 21

SubsetSum
${5, 6, 10}$$21$
${6, 15}$$21$
${10, 11}$$21$

There are 3 subsets of ${5,6,10,11,15}$ that sum to $21$.

Open this answer on its own page โ†’

2081 ยท 5 marks

Given a set $A={5,7,10,12,15,18,20}$, find the subset that sum to 35 using backtracking. [5]

  • Set $A = {5, 7, 10, 12, 15, 18, 20}$ (sorted in increasing order) - Target sum $M = 35$ - Number of elements $n = 7$ Total of all elements = $5+7+10+12+15+18+20 = 87$. --- Backtracking explores a binary state-space tree. At element $i$ we branch: - Left (include): add $wi$ to the running sum ...
Open this answer on its own page โ†’

2080 ยท 5 marks

Does backtracking give multiple solution? Trace subset sum algorithm for the set $(3, 5, 2, 4, 1)$ and sum = 8. [5]

  • Set $S = {3, 5, 2, 4, 1}$ - Target sum $X = 8$ - Number of elements $n = 5$ Yes. Backtracking systematically explores the entire state-space tree using depth-first search. It does not necessarily halt at the first feasible solution; if we ask for all solutions, it continues exploring every br...
Open this answer on its own page โ†’

2079 ยท 10 marks

What do you mean by Backtracking? Explain the backtracking algorithm for solving knapsack problem and find the solution for the problem given below and capacity of knapsack is 10 kg.

$$\begin{bmatrix} \text{Items} & 1 & 2 & 3 & 4 \ \text{Weight (w}_i\text{)} & 2 & 3 & 4 & 5 \ \text{Profit (P}_i\text{)} & 3 & 5 & 6 & 10 \end{bmatrix}$$

[10]

Show solved answer

Backtracking and 0/1 Knapsack Solution

What is Backtracking?

Backtracking is a systematic algorithmic technique that builds a solution incrementally, one component at a time, and abandons a partial candidate ("backtracks") as soon as it determines that this candidate cannot lead to a valid or optimal complete solution.

Key points:

  • It explores a state-space tree of all possible states.
  • At each node a decision is made (for knapsack: include or exclude an item).
  • A bounding function prunes branches that cannot improve upon the best solution found so far.
  • More efficient than brute force since unpromising subtrees are cut.

Backtracking Algorithm for 0/1 Knapsack

  • Each item is either taken (1) or not (0), so the state-space tree is binary.
  • Items are usually sorted by profit/weight ratio (descending) so the bound is tight.
  • At each node compute an upper bound using the fractional knapsack relaxation on remaining items. If bound <= bestProfit, prune.
Algorithm BKnap(i, cw, cp):        // cw=current weight, cp=current profit
  if cw <= W and cp > maxProfit:
      maxProfit = cp
  if i > n: return
  if Bound(i, cw, cp) > maxProfit:
      // include item i
      BKnap(i+1, cw + w[i], cp + p[i])   // only if cw+w[i] <= W
  // exclude item i
  BKnap(i+1, cw, cp)

Numerical Solution

Given Data

ItemWeight $w_i$Profit $p_i$Ratio $p_i/w_i$
1231.50
2351.67
3461.50
45102.00

Capacity $W = 10$ kg.

Sort by ratio (descending):

OrderItem$w$$p$Ratio
A45102.00
B2351.67
C1231.50
D3461.50

Bound formula

$$\text{Bound}=cp+\text{(fractional knapsack value of remaining items in remaining capacity)}$$

State-Space Tree (order 4,2,1,3)

Node 1 (root): $cw=0,\ cp=0$ Bound $=10+5+3+\tfrac{0}{4}\cdot6 = 18$ (after 4,2,1 weight $=10$, capacity full). So overall root bound $=18$.

Include Item 4: $cw=5,\ cp=10$

  • Bound: add 2 ($p=5$) โ†’ cap 2 left, add 1 ($p=3$) โ†’ cap 0. Bound $=10+5+3=18$.

    Include Item 2: $cw=8,\ cp=15$

    • Bound $=15+3=18$ (item 1 fits, cap 2).

      Include Item 1: $cw=10,\ cp=18$ - feasible, cap $=0$. $$\boxed{maxProfit = 18,\quad {4,2,1}}$$

      Exclude Item 1: $cw=8,\ cp=15$, cap 2. Bound $=15+\tfrac{2}{4}\cdot6=18$. Item 3 (w=4) does not fit; best stays 15 < 18. Pruned / no improvement.

    Exclude Item 2: $cw=5,\ cp=10$, cap 5. Bound $=10+3+\tfrac{3}{4}\cdot6=17.5 < 18$. Pruned.

Exclude Item 4: $cw=0,\ cp=0$, cap 10. Bound $=5+3+6+\tfrac{2}{5}\cdot10$? Remaining items 2,1,3 total weight $=3+2+4=9\le10$, so all fit: profit $=5+3+6=14 < 18$. Pruned.

Verification (best combination)

Items 1, 2, 4: weight $=2+3+5=10 \le 10$, profit $=3+5+10=18$. โœ”

Any other feasible set:

  • ${2,3,1}$: w $=9$, p $=14$
  • ${4,3}$: w $=9$, p $=16$
  • ${4,2}$: w $=8$, p $=15$

Maximum is 18.

Final Answer

$$\textbf{Optimal profit} = 18,\qquad \textbf{Items selected} = {1,\ 2,\ 4}$$ with total weight $10$ kg exactly filling the knapsack.

Open this answer on its own page โ†’

2076 ยท 10 marks

Explain in brief the Backtracking approach for algorithm design. How it differs with recursion? Explain the N-Queen problem and algorithm using backtracking and analyze its time complexity.[10]

--- Backtracking is an algorithmic design technique used to solve problems by building a solution incrementally, one step at a time, and abandoning (backtracking) a partial solution as soon as it is determined that it cannot lead to a valid complete solution. - Explore all possible candidates for...

Open this answer on its own page โ†’

Concept of Backtracking, Recursion vs Backtracking

2082 ยท 5 marks

Distinguish between recursion and backtracking. Using Miller-Rabin primality test, check whether 53 is prime or not? [5+0]

Feature Recursion Backtracking --------- Definition A technique where a function calls itself directly or indirectly to solve a problem An algorithmic strategy that builds a solution incrementally and abandons a partial candidate as soon as it fails the constraints Approach Breaks a problem into ...

Open this answer on its own page โ†’

2081 ยท 5 marks

Discuss about recursion and backtracking. Analyze the complexity of Miller Rabin Randomized Primality test. [5]

--- Definition: Recursion is the process of defining a problem in terms of itself. It is a process in which a function calls itself directly or indirectly to solve a problem. Key Points: - Complex problems are divided into smaller sub-problems, solved recursively, and their solutions are combined...

Open this answer on its own page โ†’

2078 ยท 5 marks

Explain the concept of backtracking. How it differ with recursion? [5]

Backtracking is a general algorithmic technique that considers searching every possible combination in order to solve a computational problem. "We have a set of several choices. If one choice from the set of choices proves incorrect, computation backtracks at the point of choice and tries another...

Open this answer on its own page โ†’

2076 ยท 5 marks

Write short notes on: a. Backtracking strategy b. Tractable and Intractable Problem [5]

--- Definition: Backtracking is a general algorithmic technique that considers searching every possible combination in order to solve a computational problem. It is used for finding solutions to computational problems where we have a set of several choices. If one choice from the set of choices p...

Open this answer on its own page โ†’