Unit 4
Unit 4
The Backtracking approach for solving the Subset Sum Problem systematically explores all subsets of
a given set to find if any subset sums to the target value. If a solution is not valid at any point, the
algorithm "backtracks" by undoing the last step and exploring other possibilities.
Process
o Include the current element in the subset and reduce the target sum by its value.
3. Base Cases:
Algorithm
2. Recursively explore both possibilities (include or exclude the element at index iii).
4. Backtrack by undoing the inclusion of the current element if it does not lead to a solution.
Pseudo-code
plaintext
Copy code
subsetSumBacktracking(S, n, T):
if T == 0:
if n == 0 or T < 0:
return true
// Exclude the current element from the subset
Time Complexity
Example
Problem Statement:
Backtracking Steps:
{12, 5, 2} 2 No 2 Continue
{5, 2} 2 No 2 Continue
Real-Life Applications
5. Example
Input:
Set S={3,34,4,12,5,2}S = \{3, 34, 4, 12, 5, 2\}S={3,34,4,12,5,2},
Target T=9
Element ↓ \ Target → 0 1 2 3 4 5 6 7 8 9
{} true false false false false false false false false false
{3} true false false true false false false false false false
{3, 34} true false false true false false false false false false
{3, 34, 4} true false false true true false false true false false
{3, 34, 4, 12} true false false true true false false true false false
{3, 34, 4, 12, 5} true false false true true true false true true true
{3, 34, 4, 12, 5, 2} true false true true true true true true true true
7. Result: dp[6][9]=true
Why is it Used?
1. Practical Applications:
2. Theoretical Importance:
o Subset Sum is a NP-complete problem, which means solving it efficiently for large
inputs is unlikely unless P=NPP = NPP=NP.
Approaches:
1. Recursive Solution:
o Base Cases:
If T=0T = 0T=0, return true (we've found a subset that sums to TTT).
If n=0n = 0n=0 and T>0T > 0T>0, return false (no more elements to include).
Pseudo-code:
plaintext
Copy code
isSubsetSum(S, n, T):
if T == 0:
return true
if n == 0:
return false
if S[n-1] > T:
dp[i][j]dp[i][j]dp[i][j] = true if there exists a subset of the first iii items that
sums to jjj, otherwise false.
Steps:
Pseudo-code:
plaintext
Copy code
isSubsetSum(S, n, T):
Create a dp[n+1][T+1]
for j = 1 to T:
if S[i-1] > j:
dp[i][j] = dp[i-1][j]
else:
return dp[n][T]
Time Complexity
1. Recursive Approach:
o Time Complexity: O(2n)O(2^n)O(2n) (since every element has two choices: include
or exclude).
o Time Complexity: O(n×T)O(n \times T)O(n×T), where nnn is the size of the set and
TTT is the target sum.
The Hamiltonian Circuit Problem is a classic graph theory problem that asks:
"Is there a cycle (closed loop) in a graph that visits every vertex exactly once?"
Formal Definition:
Hamiltonian Circuit: A cycle that visits every vertex in VVV exactly once and returns to the
starting vertex.
Difference from Eulerian Circuit:
Why is it Used?
1. Practical Applications:
2. Theoretical Importance:
Backtracking Approach:
Backtracking is one of the simplest methods to solve the Hamiltonian Circuit problem. It
systematically explores all possible vertex sequences to find a valid Hamiltonian Circuit.
Steps:
3. If all vertices are visited and there is an edge back to the starting vertex, the Hamiltonian
Circuit is found.
plaintext
Copy code
else:
path[pos] = vertex
return true
path[pos] = -1 // Backtrack
return false
return false
return false
return true
Time Complexity
Example
Problem Statement:
Graph GGG:
Vertices: {A,B,C,D}\{A, B, C, D\}{A,B,C,D}.
Edges: {(A,B),(A,C),(B,C),(C,D),(D,A)}\{(A, B), (A, C), (B, C), (C, D), (D, A)\}
{(A,B),(A,C),(B,C),(C,D),(D,A)}.
Step-by-Step Backtracking:
The N-Queens Problem is a classic combinatorial problem where you must place NNN queens on an
N×NN \times NN×N chessboard such that:
o Queens can attack any other queen in the same row, column, or diagonal.
Why is it Used?
1. Theoretical Importance:
2. Applications:
Approach: Backtracking
We attempt to place one queen per row, checking if the placement is valid:
2. Backtracking:
o If a row cannot be completed, backtrack to the previous row and try the next
column.
Steps in Backtracking
If a valid placement is found, place the queen and move to the next row.
If no valid placement exists, backtrack to the previous row and try the next column.
Pseudo-Code
plaintext
Copy code
print board
return
if board[i][col] == 1:
return False
if board[i][j] == 1:
return False
if board[i][j] == 1:
return False
return True
Python Implementation
python
Copy code
for i in range(row):
if board[i][col] == 1:
return False
i, j = row, col
if board[i][j] == 1:
return False
i -= 1
j -= 1
i, j = row, col
if board[i][j] == 1:
return False
i -= 1
j += 1
return True
if row == n:
print(line)
print()
return
board[row][col] = 0 # Backtrack
def n_queens(n):
solve_n_queens(board, 0, n)
n_queens(4)
Output
csharp
Copy code
[0, 0, 1, 0]
[1, 0, 0, 0]
[0, 0, 0, 1]
[0, 1, 0, 0]
[0, 1, 0, 0]
[0, 0, 0, 1]
[1, 0, 0, 0]
[0, 0, 1, 0]
csharp
Copy code
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
csharp
Copy code
[1, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
csharp
Copy code
[1, 0, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
4. Repeat the process for the next rows, backtracking when no valid placement exists.
Time Complexity
1. Worst Case: O(N!)O(N!)O(N!), as there are N!N!N! possible ways to place NNN queens.
1. A salesman must visit all cities exactly once and return to the starting city.
2. Manufacturing:
3. Network Design:
Backtracking is one way to solve TSP, but it is not efficient for large inputs. The idea is to:
o Mark it as visited.
4. Backtrack:
Pseudo-Code
plaintext
Copy code
return minCost
visited[nextCity] = True
return minCost
Python Implementation
python
Copy code
import sys
visited[nextCity] = True
visited[nextCity] = False
return minCost
def solve_tsp(graph):
n = len(graph)
visited = [False] * n
minCost = sys.maxsize
graph = [
# Solve TSP
result = solve_tsp(graph)
Input Example
A B C D
A 0 10 15 20
B 10 0 35 25
A B C D
C 15 35 0 30
D 20 25 30 0
Output
css
Copy code
1. Start at City A.
2. Explore paths:
o ...
Time Complexity
Optimized Approaches
2. Heuristic Algorithms:
1. Reducibility
What is Reducibility?
Reducibility is a concept where one problem can be transformed into another problem.
If problem AAA can be reduced to problem BBB, solving BBB automatically solves AAA.
Why is it Important?
1. There exists a polynomial-time algorithm to transform any instance of AAA into BBB.
Example:
Reducing the 3SAT problem to the Clique problem to prove that the Clique problem is NP-
complete.
2. NP-Completeness
What is NP-Completeness?
Why is it Important?
If any NP-complete problem is solved in polynomial time, then P=NPP = NPP=NP, meaning all
NP problems can be solved efficiently.
3SAT: A special case of SAT where each clause has exactly 3 literals.
Vertex Cover: Finding a minimum set of vertices that cover all edges in a graph.
3. NP-Hard
What is NP-Hard?
NP-Hard problems do not need to be in NP (i.e., their solutions may not be verifiable in
polynomial time).
Examples:
Travelling Salesman Problem (TSP): Finding the shortest route that visits all cities.
NP-Complete Hardest problems in NP; both in NP and NP-Hard. SAT, 3SAT, Vertex Cover
NP-Hard As hard as NP-Complete, but not necessarily in NP. TSP, Halting Problem
Given a boolean circuit with AND, OR, and NOT gates, determine if there is an input that
makes the circuit output true.
Why is it Important?
Complexity:
NP-complete.
Use Case:
6. 3SAT Problem
What is 3SAT?
A specific version of the SAT problem where each clause has exactly 3 literals.
Why is it Important?
Example:
Complexity:
NP-complete.
Use Case:
A set of vertices in a graph such that every edge is incident to at least one vertex in the set.
Why is it Important?
Example:
Complexity:
NP-complete.
8. Clique Problem
What is a Clique?
Why is it Important?
Example:
Complexity:
NP-complete.
9. Cook's Theorem
Why is it Important?
It was the first theorem to prove the existence of NP-complete problems, establishing the
foundation of complexity theory.
Proof Outline:
Use Case:
1. Backtracking:
o Example: TSP.
4. Reduction:
Introduction to Computability
What is Computability?
A problem is computable if there exists an algorithm that can provide a solution in a finite
number of steps.
1. Decidability:
o A problem is decidable if an algorithm exists that provides a "yes" or "no" answer for
every possible input in a finite time.
2. Undecidability:
o Example: The Halting Problem, which determines if a program will halt or run
forever.
3. Reduction:
Polynomial-time Verification
2. Verification involves checking whether the provided solution satisfies the problem's
constraints.
Example:
Problem: Is there a subset of numbers from a given set that sums to SSS?
Given a solution (subset), verifying whether it sums to SSS can be done in polynomial time.
Classes of Problems:
1. P (Polynomial Time):
NP-Completeness
What is NP-Completeness?
If any NP-complete problem can be solved in polynomial time, then all NP problems can also
be solved in polynomial time (i.e., P=NPP = NPP=NP).
Key Properties of NP-Complete Problems
1. Reduction:
o If a problem AAA is reducible to another problem BBB in polynomial time and BBB is
solvable, then AAA is also solvable.
o The Satisfiability (SAT) Problem was the first problem proven to be NP-complete
(Cook-Levin Theorem).
o Knapsack Problem.
2. Reduction:
o Show that the known NP-complete problem can be reduced to the new problem in
polynomial time.
Real-life Applications
1. Cryptography:
2. Operations Research:
3. Artificial Intelligence:
4. Network Design:
Problem Description:
Given a boolean formula, is there an assignment of variables that makes the formula true?
Optimized algorithms or heuristics (e.g., Branch and Bound, Approximation) are used for
practical purposes.
1. Reducibility
Solution:
o A 3SAT problem has a boolean formula in conjunctive normal form (CNF) where each
clause has exactly 3 literals.
o A clique is a subset of vertices in a graph such that every two vertices are connected
by an edge.
o The Clique Problem asks whether a graph contains a clique of size kkk.
3. Reduction Steps:
4. Result:
Problem: Determine if a given boolean circuit can output TRUE for some input combination.
Solution:
o Example:
css
Copy code
A → AND → B
NOT ← OR → C
2. Steps:
3. Complexity:
3. 3SAT
Solution:
1. Example:
2. Backtracking Algorithm:
o Assign truth values to variables iteratively.
3. Result:
4. Vertex Cover
Problem: Find the minimum set of vertices that cover all edges in a graph.
Solution:
1. Graph Example:
o Graph:
css
Copy code
A—B
| |
C D
2. Steps:
3. Result:
4. Approximation Algorithm:
o Pick any edge, add both endpoints to the cover, and remove all adjacent edges.
5. Clique
Solution:
1. Graph Example:
o Edges: (A,B),(B,C),(C,A),(D,E)(A, B), (B, C), (C, A), (D, E)(A,B),(B,C),(C,A),(D,E).
o Graph:
mathematica
Copy code
A—B
\ |
C D—E
2. Steps:
3. Result:
6. Cook's Theorem
Solution:
1. Belongs to NP:
2. Reduction:
3. Result:
o Cook’s Theorem established that SAT is NP-complete, forming the basis for NP-
completeness proofs.
Problem: Find the shortest route that visits all cities and returns to the starting city.
Solution:
1. Input:
o Distance matrix:
css
Copy code
A B C
A 0 1 2
B 1 0 3
C 2 3 0
2. Exact Algorithm:
3. Approximation Algorithm:
o Nearest Neighbor:
4. Result:
5. Complexity:
o Exact: O(n!)O(n!)O(n!).
Classification Examples:
NP Subset-Sum, 3SAT
Key Differences:
PPP: Problems solvable in polynomial time.
9. Complexity Comparison