Introduction
Greedy and Backtracking are two powerful algorithmic paradigms for solving optimization and search problems. While they approach problems differently, both are essential techniques in a programmer’s toolkit.
Greedy algorithms make locally optimal choices at each step, hoping to find a global optimum. Backtracking explores all possible solutions by building candidates incrementally and abandoning candidates that cannot lead to valid solutions.
In this article, we’ll explore these techniques through practical LeetCode problems, providing clean, well-explained solutions in both C# and Python.
What is Backtracking?
Backtracking is a systematic method for solving problems by:
- Building solutions incrementally
- Abandoning partial solutions that cannot lead to valid complete solutions
- Exploring all possible paths through a state space
- Using recursion to explore and backtrack
Key Components of Backtracking:
1. Choice At each step, make a choice (add an element, place a character, etc.)
2. Constraints Check if the current choice is valid according to problem constraints
3. Goal Check if we’ve reached a complete solution
4. Backtrack If the current path cannot lead to a solution, undo the last choice and try alternatives
Backtracking Template:
void Backtrack(result, currentSolution, remainingChoices)
{
// Base case: check if solution is complete
if (IsComplete(currentSolution))
{
result.Add(currentSolution);
return;
}
// Try each possible choice
foreach (choice in remainingChoices)
{
// Make choice
currentSolution.Add(choice);
// Check constraints
if (IsValid(currentSolution))
{
// Explore further
Backtrack(result, currentSolution, GetRemainingChoices());
}
// Backtrack: undo choice
currentSolution.Remove(choice);
}
}
When to Use Backtracking:
- Combinatorial Problems: Permutations, combinations, subsets
- Constraint Satisfaction: Problems with multiple constraints
- Search Problems: Finding all solutions or one solution
- Decision Problems: Problems requiring exploring all possibilities
What is Greedy?
Greedy algorithms make the best choice at each step without considering future consequences. They:
- Make locally optimal choices
- Hope these choices lead to a globally optimal solution
- Don’t backtrack or reconsider previous choices
Greedy Strategy:
- Greedy Choice Property: A global optimum can be reached by making locally optimal choices
- Optimal Substructure: An optimal solution contains optimal solutions to subproblems
When to Use Greedy:
- Optimization Problems: Finding minimum/maximum
- Interval Problems: Scheduling, activity selection
- Graph Problems: Minimum spanning tree, shortest path (in some cases)
- When Greedy Works: Problems where local optimum leads to global optimum
Problem 1: Permutations
Problem Statement
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Input: nums = [1]
Output: [[1]]
Understanding the Problem
A permutation is an arrangement of all elements in a specific order. We need to generate all possible arrangements where each element appears exactly once.
Solution Strategy
Backtracking Approach:
- Build permutations incrementally
- For each position, try each unused element
- Add element to current permutation
- Recursively build the rest
- Remove element (backtrack) and try next option
C# Solution
public class Solution
{
public IList<IList<int>> Permute(int[] nums)
{
IList<IList<int>> result = new List<IList<int>>();
Backtrack(result, new List<int>(), nums);
return result;
}
private void Backtrack(IList<IList<int>> result, List<int> tempList, int[] nums)
{
// Base case: permutation is complete
if (tempList.Count == nums.Length)
{
result.Add(new List<int>(tempList));
return;
}
// Try each element that hasn't been used
for (int i = 0; i < nums.Length; i++)
{
// Skip if element already in current permutation
if (tempList.Contains(nums[i]))
continue;
// Make choice: add element
tempList.Add(nums[i]);
// Explore: recursively build rest of permutation
Backtrack(result, tempList, nums);
// Backtrack: remove last element
tempList.RemoveAt(tempList.Count - 1);
}
}
}
Python 3 Solution
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def backtrack(start, end):
# Base case: permutation is complete
if start == end:
result.append(nums[:])
return
# Try each element from start to end
for i in range(start, end):
# Make choice: swap elements
nums[start], nums[i] = nums[i], nums[start]
# Explore: recursively build rest of permutation
backtrack(start + 1, end)
# Backtrack: undo swap
nums[start], nums[i] = nums[i], nums[start]
result = []
backtrack(0, len(nums))
return result
Complexity Analysis
- Time Complexity: O(n! × n) where n is the number of elements
- There are n! permutations
- Each permutation takes O(n) to build
- Space Complexity: O(n) for recursion stack and temporary list
Key Insight
The Python solution uses an in-place swapping approach, which is more space-efficient. The C# solution uses a temporary list to track the current permutation.
Problem 2: Subsets
Problem Statement
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Input: nums = [0]
Output: [[],[0]]
Understanding the Problem
A subset is any combination of elements from the array, including the empty set. We need to generate all possible subsets.
Solution Strategy
Backtracking Approach:
- For each element, we have two choices: include it or exclude it
- Build subsets incrementally
- Add current subset to result at each step (not just at the end)
- Try including current element, then try excluding it
C# Solution
public class Solution
{
public IList<IList<int>> Subsets(int[] nums)
{
IList<IList<int>> result = new List<IList<int>>();
Backtrack(result, new List<int>(), nums, 0);
return result;
}
private void Backtrack(IList<IList<int>> result, List<int> tempList, int[] nums, int start)
{
// Add current subset to result (all subsets are valid)
result.Add(new List<int>(tempList));
// Try each element starting from 'start' index
for (int i = start; i < nums.Length; i++)
{
// Make choice: include current element
tempList.Add(nums[i]);
// Explore: recursively build subsets with remaining elements
Backtrack(result, tempList, nums, i + 1);
// Backtrack: remove last element
tempList.RemoveAt(tempList.Count - 1);
}
}
}
Python 3 Solution
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def backtrack(result: List[List[int]], chosen: List[int], remaining: List[int]):
# Base case: no more elements to choose
if not remaining:
result.append(chosen[:])
return
# Take first element from remaining
element = remaining.pop(0)
# Choice 1: Include element
chosen.append(element)
backtrack(result, chosen, remaining)
chosen.pop()
# Choice 2: Exclude element
backtrack(result, chosen, remaining)
# Backtrack: restore remaining list
remaining.insert(0, element)
result = []
backtrack(result, [], nums)
return result
Complexity Analysis
- Time Complexity: O(2ⁿ × n) where n is the number of elements
- There are 2ⁿ subsets
- Each subset takes O(n) to build
- Space Complexity: O(n) for recursion stack and temporary list
Key Insight
Unlike permutations, we add the current subset to results at each recursive call, not just at the base case. This ensures we capture all subsets of different sizes.
Problem 3: Combination Sum
Problem Statement
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
Example
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Understanding the Problem
We need to find all combinations (order doesn’t matter) that sum to target. Elements can be reused, so we need to explore all possibilities.
Solution Strategy
Backtracking Approach:
- Try each candidate starting from current index (allows reuse)
- Add candidate to current combination
- Recursively search with updated target
- If target becomes negative, backtrack (invalid path)
- If target becomes 0, add combination to result
- Remove candidate and try next
C# Solution
public class Solution
{
public IList<IList<int>> CombinationSum(int[] candidates, int target)
{
IList<IList<int>> result = new List<IList<int>>();
Backtrack(result, new List<int>(), candidates, target, 0);
return result;
}
private void Backtrack(IList<IList<int>> result, List<int> tempList, int[] candidates, int remain, int start)
{
// Base case: invalid path (sum exceeds target)
if (remain < 0)
{
return;
}
// Base case: valid combination found
else if (remain == 0)
{
result.Add(new List<int>(tempList));
return;
}
else
{
// Try each candidate starting from 'start' (allows reuse)
for (int i = start; i < candidates.Length; i++)
{
// Make choice: add candidate
tempList.Add(candidates[i]);
// Explore: recursively search with updated target
// Pass 'i' as start to allow reusing current candidate
Backtrack(result, tempList, candidates, remain - candidates[i], i);
// Backtrack: remove last candidate
tempList.RemoveAt(tempList.Count - 1);
}
}
}
}
Python 3 Solution
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def backtrack(candidates: List[int], target: int, tempList: List[int], result: List[List[int]]):
# Base case: invalid path (sum exceeds target)
if target < 0:
return
# Base case: valid combination found
if target == 0:
result.append(tempList[:])
return
# Try each candidate
for i, num in enumerate(candidates):
# Explore: recursively search with updated target
# Pass candidates[i:] to allow reusing current candidate
backtrack(candidates[i:], target - num, tempList + [num], result)
result = []
backtrack(candidates, target, [], result)
return result
Complexity Analysis
- Time Complexity: O(2^target) in worst case
- Each candidate can be chosen multiple times
- In worst case, we explore all combinations
- Space Complexity: O(target) for recursion stack (depth is at most target/min(candidates))
Key Insight
By passing i as the start index (C#) or candidates[i:] (Python), we allow reusing the same candidate multiple times while avoiding duplicate combinations.
Problem 4: Generate Parentheses
Problem Statement
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Input: n = 1
Output: ["()"]
Understanding the Problem
We need to generate all valid combinations of n pairs of parentheses. A combination is valid if:
- Every opening parenthesis has a matching closing parenthesis
- At any point, number of closing parentheses ≤ number of opening parentheses
Solution Strategy
Backtracking Approach:
- Track number of open and close parentheses used
- Add ‘(‘ if we haven’t used all n open parentheses
- Add ‘)’ if we have more open than close (valid to close)
- When we’ve used n pairs, add to result
C# Solution
public class Solution
{
public IList<string> GenerateParenthesis(int n)
{
IList<string> result = new List<string>();
Backtrack(result, "", 0, 0, n);
return result;
}
private void Backtrack(IList<string> result, string str, int open, int close, int max)
{
// Base case: used all n pairs
if (str.Length == max * 2)
{
result.Add(str);
return;
}
// Choice 1: Add opening parenthesis if available
if (open < max)
{
Backtrack(result, str + "(", open + 1, close, max);
}
// Choice 2: Add closing parenthesis if valid (more opens than closes)
if (close < open)
{
Backtrack(result, str + ")", open, close + 1, max);
}
}
}
Python 3 Solution
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def backtrack(leftRemain, rightRemain, path, result):
# Invalid state: more rights than lefts, or negative counts
if leftRemain > rightRemain or leftRemain < 0 or rightRemain < 0:
return
# Base case: used all parentheses
if leftRemain == 0 and rightRemain == 0:
result.append(path)
return
# Choice 1: Add opening parenthesis
backtrack(leftRemain - 1, rightRemain, path + "(", result)
# Choice 2: Add closing parenthesis
backtrack(leftRemain, rightRemain - 1, path + ")", result)
result = []
backtrack(n, n, "", result)
return result
Complexity Analysis
- Time Complexity: O(4ⁿ / √n) – Catalan number
- Space Complexity: O(n) for recursion stack
Key Insight
The constraint close < open ensures we never add more closing parentheses than opening ones, which guarantees valid parentheses combinations.
Backtracking Patterns
Pattern 1: Permutation Pattern
Generate all arrangements:
- Try each unused element at each position
- Track used elements
- Backtrack after exploring
Example: Permutations
Pattern 2: Subset Pattern
Generate all combinations:
- For each element: include or exclude
- Add current state to results
- Use start index to avoid duplicates
Example: Subsets
Pattern 3: Constraint Satisfaction
Generate valid solutions:
- Check constraints before making choice
- Prune invalid paths early
- Track state variables (counts, sums, etc.)
Example: Generate Parentheses, Combination Sum
Pattern 4: Incremental Building
Build solution step by step:
- Make choice
- Check if complete
- Explore further or backtrack
Example: All backtracking problems
Key Takeaways
Backtracking Best Practices:
1. Identify the Choice Space What choices do we make at each step? (include/exclude, which element, etc.)
2. Define Constraints What makes a partial solution invalid? Check constraints early to prune.
3. Determine Base Case When is the solution complete? Add to results at base case.
4. Implement Backtracking
- Make choice
- Explore recursively
- Undo choice (backtrack)
5. Avoid Duplicates Use start index or track used elements to avoid generating duplicate solutions.
When to Use Backtracking:
- All Solutions: When you need to find all possible solutions
- Combinatorial Problems: Permutations, combinations, subsets
- Constraint Satisfaction: Problems with multiple constraints
- Search Problems: When exploring all possibilities is necessary
When to Use Greedy:
- Optimization: When local optimum leads to global optimum
- Single Solution: When you need one optimal solution
- Efficiency: When O(n log n) or O(n) is required
- Proven Greedy: Problems with proven greedy properties
Common Backtracking Mistakes:
- Not Backtracking: Forgetting to undo choices
- Missing Constraints: Not checking constraints before exploring
- Duplicate Solutions: Not properly tracking used elements
- Inefficient Pruning: Not pruning invalid paths early
- Wrong Base Case: Incorrect termination condition
Optimization Tips:
1. Early Pruning Check constraints before making recursive calls to avoid unnecessary exploration.
2. Memoization Cache results for overlapping subproblems when applicable.
3. Sort Input Sorting can help avoid duplicates and enable early pruning.
4. State Tracking Use efficient data structures (sets, arrays) to track state.
Greedy vs Backtracking
Greedy:
- Makes locally optimal choices
- Doesn’t backtrack
- Faster (often O(n log n) or O(n))
- May not find optimal solution
- Used for optimization problems
Backtracking:
- Explores all possibilities
- Backtracks when needed
- Slower (often exponential)
- Finds all solutions
- Used for search/combinatorial problems
Conclusion
Backtracking and Greedy are powerful techniques for solving different types of problems. Backtracking is ideal when you need to explore all possibilities or find all solutions, while Greedy works well for optimization problems where local choices lead to global optimum.
Key patterns to remember:
- Backtracking Template: Make choice → Explore → Undo choice
- Constraint Checking: Validate before exploring
- Base Cases: Know when solution is complete
- Avoiding Duplicates: Use indices or tracking mechanisms
Practice identifying when to use backtracking vs greedy, and master the backtracking template. The more you practice, the better you’ll become at recognizing problem patterns and applying the right technique.
Remember: Backtracking is about systematic exploration with pruning, while Greedy is about making the best local choice. Choose the right tool for the right problem.
Happy coding!
