Data Structures and Algorithms • C# examples
Backtracking, Pruning, and Search Trees
Explore candidate solutions incrementally and abandon branches that cannot succeed.
Concept
Backtracking builds a partial solution, checks constraints, and reverses the choice before trying another branch. Pruning is safe only when the rejected partial state cannot lead to a valid answer. Search trees can grow exponentially, so ordering choices and deriving bounds matter.
How to approach it
Keep a clear choose-explore-unchoose structure; make state restoration correct even when a branch returns early.
Complexity
Worst-case often exponential; pruning may improve practical work without changing the worst-case bound.
C# example
void Search(int position)
{
if (position == values.Length) { SaveSolution(); return; }
foreach (var choice in Choices(position))
{
if (!IsPromising(choice)) continue;
Apply(choice);
Search(position + 1);
Undo(choice);
}
}
Expected result or behavior
Each candidate extends the current partial state only when it remains promising.
Practice exercise
Use the template to generate subsets and identify when a subset should be recorded.
Key takeaway: Pruning is a correctness-preserving proof that a branch cannot improve or complete a solution.