what are the common c++ incursion backtracking questions that professor give on final…
- User
what are the common c++ incursion backtracking questions that professor give on final exam and what are the solution to them?
- Assistant
what are the common c++ incursion backtracking questions that professor give on final exam and what are the solution to them?
Certainly! Recursion and backtracking are fundamental techniques in C++ programming, especially for solving problems involving combinations, permutations, and exploring multiple possibilities. Professors often include a variety of these problems in final exams to test students' understanding and problem-solving skills. Below are some common C++ recursion and backtracking questions frequently seen in final exams, along with detailed explanations and example solutions.
Problem:
Write a recursive function to calculate the factorial of a non-negative integer n.
Solution:
The factorial of n (denoted as n!) is the product of all positive integers less than or equal to n. It’s defined as:
0! = 1n! = n * (n-1)! for n > 0C++ Code:
#include <iostream>
using namespace std;
// Recursive function to calculate factorial
long long factorial(int n) {
if (n == 0 || n == 1)
return 1; // Base cases
else
return n * factorial(n - 1); // Recursive call
}
int main(){
int number;
cout << "Enter a non-negative integer: ";
cin >> number;
if (number < 0)
cout << "Factorial is not defined for negative numbers." << endl;
else
cout << number << "! = " << factorial(number) << endl;
return 0;
}
Problem:
Write a recursive function to find the n-th Fibonacci number. The sequence starts with 0 and 1.
Solution: The Fibonacci sequence is defined as:
Fib(0) = 0Fib(1) = 1Fib(n) = Fib(n-1) + Fib(n-2) for n > 1C++ Code:
#include <iostream>
using namespace std;
// Recursive function to calculate Fibonacci number
long long fibonacci(int n){
if(n == 0)
return 0; // Base case
else if(n == 1)
return 1; // Base case
else
return fibonacci(n-1) + fibonacci(n-2); // Recursive call
}
int main(){
int terms;
cout << "Enter the term number: ";
cin >> terms;
if(terms < 0)
cout << "Invalid input." << endl;
else
cout << "Fibonacci(" << terms << ") = " << fibonacci(terms) << endl;
return 0;
}
Note: This recursive approach has exponential time complexity. For large n, consider using dynamic programming or an iterative approach to optimize performance.
Problem:
Place N queens on an N x N chessboard such that no two queens threaten each other. Print all possible solutions.
Solution: Use backtracking to place queens one row at a time, ensuring that each placement is safe (i.e., no two queens share the same row, column, or diagonal).
C++ Code:
#include <bits/stdc++.h>
using namespace std;
// Function to check if it's safe to place a queen at board[row][col]
bool isSafe(int row, int col, vector<string> &board, int n){
// Check column
for(int i=0; i<row; i++)
if(board[i][col] == 'Q')
return false;
// Check upper-left diagonal
for(int i=row-1, j=col-1; i>=0 && j>=0; i--, j--)
if(board[i][j] == 'Q')
return false;
// Check upper-right diagonal
for(int i=row-1, j=col+1; i>=0 && j<n; i--, j++)
if(board[i][j] == 'Q')
return false;
return true;
}
// Backtracking function to solve N-Queens
void solveNQueens(int row, vector<string> &board, vector<vector<string>> &solutions, int n){
if(row == n){
solutions.push_back(board);
return;
}
for(int col=0; col<n; col++){
if(isSafe(row, col, board, n)){
board[row][col] = 'Q'; // Place queen
solveNQueens(row+1, board, solutions, n); // Recurse for next row
board[row][col] = '.'; // Backtrack
}
}
}
int main(){
int n;
cout << "Enter the number of queens: ";
cin >> n;
vector<string> board(n, string(n, '.')); // Initialize board with dots
vector<vector<string>> solutions;
solveNQueens(0, board, solutions, n); // Start solving from row 0
cout << "Total solutions: " << solutions.size() << endl;
for(auto &sol : solutions){
for(auto &row : sol)
cout << row << endl;
cout << endl;
}
return 0;
}
Problem: Generate all permutations of a given string.
Solution: Use recursion by fixing one character at a time and swapping it with the current position, then recursively permute the remaining substring.
C++ Code:
#include <bits/stdc++.h>
using namespace std;
// Recursive function to generate permutations
void permute(string s, int l, int r, vector<string> &result){
if(l == r){
result.push_back(s);
return;
}
for(int i=l; i<=r; i++){
swap(s[l], s[i]); // Swap current character with character at position i
permute(s, l+1, r, result); // Recurse for the next character
// No need to swap back since strings are passed by value
}
}
int main(){
string str;
cout << "Enter a string: ";
cin >> str;
vector<string> permutations;
permute(str, 0, str.length()-1, permutations);
cout << "Total permutations: " << permutations.size() << endl;
for(auto &p : permutations)
cout << p << endl;
return 0;
}
Problem: Given a set of integers and a target sum, find all subsets that sum up to the target value.
Solution: Use backtracking to explore all possible subsets by including or excluding each element and check if the current subset sums to the target.
C++ Code:
#include <bits/stdc++.h>
using namespace std;
// Backtracking function to find subsets
void subsetSum(int index, int target, vector<int> &arr, vector<int> ¤t, vector<vector<int>> &result){
if(target == 0){
result.push_back(current);
return;
}
if(target < 0 || index >= arr.size())
return;
// Include current element
current.push_back(arr[index]);
subsetSum(index+1, target - arr[index], arr, current, result);
// Exclude current element
current.pop_back();
subsetSum(index+1, target, arr, current, result);
}
int main(){
int n, target;
cout << "Enter number of elements: ";
cin >> n;
vector<int> arr(n);
cout << "Enter elements: ";
for(auto &x : arr)
cin >> x;
cout << "Enter target sum: ";
cin >> target;
vector<int> current;
vector<vector<int>> result;
subsetSum(0, target, arr, current, result);
cout << "Subsets that sum up to " << target << ":\n";
for(auto &subset : result){
for(auto &num : subset)
cout << num << " ";
cout << endl;
}
return 0;
}
Problem:
Given a 2D maze represented by a grid, find a path from the top-left corner (0,0) to the bottom-right corner (N-1,M-1) avoiding blocked cells.
Solution: Use backtracking to explore all possible paths by moving in four directions (up, down, left, right) and mark cells as visited to avoid cycles.
C++ Code:
#include <bits/stdc++.h>
using namespace std;
// Function to check if a cell is safe to visit
bool isSafe(int x, int y, vector<vector<int>> &maze, vector<vector<bool>> &visited, int N, int M){
return (x >=0 && x < N && y >=0 && y < M && maze[x][y] == 1 && !visited[x][y]);
}
// Backtracking function to solve the maze
bool solveMazeUtil(int x, int y, vector<vector<int>> &maze, vector<vector<bool>> &visited, vector<pair<int,int>> &path, int N, int M){
// If destination is reached
if(x == N-1 && y == M-1){
path.emplace_back(make_pair(x, y));
return true;
}
// Check if current position is safe
if(isSafe(x, y, maze, visited, N, M)){
// Mark the cell as visited
visited[x][y] = true;
path.emplace_back(make_pair(x, y));
// Move Down
if(solveMazeUtil(x+1, y, maze, visited, path, N, M))
return true;
// Move Right
if(solveMazeUtil(x, y+1, maze, visited, path, N, M))
return true;
// Move Up
if(solveMazeUtil(x-1, y, maze, visited, path, N, M))
return true;
// Move Left
if(solveMazeUtil(x, y-1, maze, visited, path, N, M))
return true;
// Backtrack
path.pop_back();
visited[x][y] = false;
}
return false;
}
int main(){
int N, M;
cout << "Enter maze dimensions (N M): ";
cin >> N >> M;
vector<vector<int>> maze(N, vector<int>(M));
cout << "Enter the maze (1 for open, 0 for blocked):\n";
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
cin >> maze[i][j];
vector<vector<bool>> visited(N, vector<bool>(M, false));
vector<pair<int,int>> path;
if(solveMazeUtil(0, 0, maze, visited, path, N, M)){
cout << "Path to solve the maze:\n";
for(auto &p : path)
cout << "(" << p.first << "," << p.second << ") ";
cout << endl;
}
else{
cout << "No path found." << endl;
}
return 0;
}
Problem:
Solve the Tower of Hanoi problem for n disks, printing the sequence of moves required to move all disks from source to destination.
Solution:
Use recursion to move n-1 disks from source to auxiliary peg, move the n-th disk to the destination, and then move the n-1 disks from auxiliary to destination.
C++ Code:
#include <bits/stdc++.h>
using namespace std;
// Recursive function to solve Tower of Hanoi
void towerOfHanoi(int n, char source, char auxiliary, char destination){
if(n == 1){
cout << "Move disk 1 from " << source << " to " << destination << endl;
return;
}
// Move n-1 disks from source to auxiliary
towerOfHanoi(n-1, source, destination, auxiliary);
// Move the nth disk from source to destination
cout << "Move disk " << n << " from " << source << " to " << destination << endl;
// Move the n-1 disks from auxiliary to destination
towerOfHanoi(n-1, auxiliary, source, destination);
}
int main(){
int n;
cout << "Enter number of disks: ";
cin >> n;
towerOfHanoi(n, 'A', 'B', 'C'); // A: Source, B: Auxiliary, C: Destination
return 0;
}
Problem: Given a partially filled Sudoku grid, fill the grid following Sudoku rules.
Solution: Use backtracking to try possible numbers in empty cells and backtrack if a number doesn't lead to a solution.
C++ Code:
#include <bits/stdc++.h>
using namespace std;
// Function to check if placing a number is valid
bool isValid(vector<vector<char>> &board, int row, int col, char c){
for(int i=0; i<9; i++){
// Check row
if(board[row][i] == c)
return false;
// Check column
if(board[i][col] == c)
return false;
// Check 3x3 subgrid
if(board[3*(row/3) + i/3][3*(col/3) + i%3] == c)
return false;
}
return true;
}
// Backtracking function to solve Sudoku
bool solveSudokuUtil(vector<vector<char>> &board){
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j] == '.'){
for(char c = '1'; c <= '9'; c++){
if(isValid(board, i, j, c)){
board[i][j] = c;
if(solveSudokuUtil(board))
return true;
board[i][j] = '.'; // Backtrack
}
}
return false; // Trigger backtracking
}
}
}
return true; // Solved
}
int main(){
vector<vector<char>> board(9, vector<char>(9));
cout << "Enter the Sudoku puzzle row by row, use '.' for empty cells:\n";
for(int i=0;i<9;i++)
for(int j=0;j<9; j++)
cin >> board[i][j];
if(solveSudokuUtil(board)){
cout << "Solved Sudoku:\n";
for(auto &row : board){
for(auto &c : row)
cout << c << ' ';
cout << endl;
}
}
else{
cout << "No solution exists." << endl;
}
return 0;
}
Problem:
Generate all binary strings of length n.
Solution:
Use recursion to append 0 or 1 at each step until the string reaches the desired length.
C++ Code:
#include <bits/stdc++.h>
using namespace std;
// Recursive function to generate binary strings
void generateBinaryStrings(int n, string current, vector<string> &result){
if(current.length() == n){
result.push_back(current);
return;
}
// Append '0' and recurse
generateBinaryStrings(n, current + "0", result);
// Append '1' and recurse
generateBinaryStrings(n, current + "1", result);
}
int main(){
int n;
cout << "Enter the length of binary strings: ";
cin >> n;
vector<string> binaryStrings;
generateBinaryStrings(n, "", binaryStrings);
cout << "Total binary strings: " << binaryStrings.size() << endl;
for(auto &s : binaryStrings)
cout << s << endl;
return 0;
}
Problem: Given an array of distinct integers and a target sum, find all unique combinations that sum up to the target. Each number in the array may be used an unlimited number of times.
Solution: Use backtracking to explore all possible combinations by including the current number multiple times or moving to the next number.
C++ Code:
#include <bits/stdc++.h>
using namespace std;
// Backtracking function to find combinations
void combinationSumUtil(int index, int target, vector<int> &arr, vector<int> ¤t, vector<vector<int>> &result){
if(target == 0){
result.push_back(current);
return;
}
if(target < 0 || index == arr.size())
return;
// Include the current element
current.push_back(arr[index]);
combinationSumUtil(index, target - arr[index], arr, current, result);
// Exclude the current element
current.pop_back();
combinationSumUtil(index +1, target, arr, current, result);
}
int main(){
int n, target;
cout << "Enter number of elements: ";
cin >> n;
vector<int> arr(n);
cout << "Enter distinct elements: ";
for(auto &x : arr)
cin >> x;
cout << "Enter target sum: ";
cin >> target;
vector<int> current;
vector<vector<int>> result;
combinationSumUtil(0, target, arr, current, result);
cout << "Combinations that sum up to " << target << ":\n";
for(auto &comb : result){
for(auto &num : comb)
cout << num << " ";
cout << endl;
}
return 0;
}
Understanding Base Cases: Recursion relies heavily on base cases to terminate. Always ensure that the base cases correctly handle the simplest inputs to prevent infinite recursion.
Backtracking Principles: When using backtracking, make sure to undo (backtrack) any changes made to the state (like removing an element from the current path) before returning to explore other possibilities.
Optimization: Some recursive solutions (like the plain Fibonacci sequence) can have exponential time complexity. Consider optimizing using techniques like memoization or dynamic programming where applicable.
Recursive vs Iterative: While recursion provides a clean and intuitive way to solve problems, it may not always be the most efficient approach in terms of time and space. Understanding when to use recursion versus iterative methods is crucial.
Practice Variations: Many problems have multiple variations (e.g., subset sum with or without duplicates, N-Queens with different constraints). Practicing these variations will enhance your problem-solving skills.
By familiarizing yourself with these common recursion and backtracking problems and practicing their solutions, you'll be well-prepared to tackle similar challenges in your C++ final exams. Remember to write clean and efficient code, and always test your solutions with different input cases to ensure their correctness.
Not yet included in a published release.