Backtracking Flashcards
What is backtracking ??
In a given problem, if all possible solutions is to be found, then we can apply backtracking.
What is bounded function or constraint ?
when finding the solution, there will be constraints can be enforced. Solution which satisfies the constraint will be considered as one of the solution. If the constraint is not met, the path/track will not be explored further. will move onto next possible solution.
Which data structure used ?
State-space tree can be used to track the path traveled to find the solution
Which algorithm most commonly used in backtracking ?
DFS with Recursive
Backtracking problems
N-Queens problem
Maze
sudoku
Backtracking Vs. Branch-and-Bound
Backtracking uses DFS to construct the solution
Branch and Bound used BFS.
N Queens problem - Backtracking
- Problem
Place āNā queens in a N*N matrix. - Constraints/ Bounded Functions
- Queens cannot be placed in same row, column, diagonally.
- Start with Qi and place it in a matrix and place other queens by applying constraint for every move, if it satisfies move on to next queen, if not move to next place for the queen.
Sum of subsets - Backtracking
- Problem
In a given array of numbers and target sum, find all possible subset of numbers which adds upto exactly the target sum. - Constraints
- added weight cannot exceed target sum
- remaining weight has to be greater than zero before exploring the path downwards.
- Approach.
- maintain currSum , remainingSum
- Add numbers from array by adding the weight to currSum and subtracting it from remaining sum. Before moving further down, apply boundary conditions.
if remaining sum < targetSum, continue adding numbers.
if remainingSum is > targetSum , try by not adding the number.