Downloadfile 2
Downloadfile 2
● D ynamic Programming (DP) is a method to solve problems by ● T he 0/1 Knapsack Problem is a combinatorial optimization
breaking them into smaller subproblems problem where the goal is to select a subset of items with given
● s olving each subproblem once, and reusing their results to weights and values to maximize the total value without
avoid repeating work. exceeding a weight limit.
● Unlike the Fractional Knapsack Problem, where items can be
Seen
divided, in the 0/1 Knapsack Problem, each item can either be
“Instead of solving the same problem repeatedly (like in recursion), DP taken whole or left out.
stores the results of solved subproblems in a table (array) and uses
them when needed.” Example
Seen
3.Return dp[n ][W]
“Dynamic Programming avoids redundant calculations by storing
results, while recursion may repeatedly solve the same subproblems
without storing results.”
Quantum 4.17
Seen
“Dynamic Programming ensures global optimality by solving all
Approaches in Dynamic Programming (DP):
subproblems, while Greedy focuses on local optimality, which may not
.Top-Down Approach (Memoization)
1 guarantee the best solution.”
Solve the problem recursively and store the results of subproblems
i n a cache (usually an array or hash table) to reuse later. Floyd Warshal Alogrithm
intfib( intn,vector<int>&m emo) {
● I t is a dynamic programming algorithm used to discover the
if( n<=1) returnn;//B ase cases
s hortest paths in a weighted graph
if( m emo[n]!=-1) returnm emo[n];//Use storedvalueifavailable
m emo[n]= fib( n-1,m emo) +fib( n-2,m emo) ;//Store result ● I n which includes both positive & negative weight cycles.
returnm emo[n]; ● I t is also called all pair shortest path algorithm
} ● Time complexity: O(N3) &space complexity:O(V2)
.Bottom-Up Approach (Tabulation)
2 Algorithm
Solve smaller subproblems first iteratively, then use these solutions .Create a matri x'd i st'o f s i ze VxV( Vi s n umbero f vertices )
1
to build up the solution to the main problem. a ndi ni tia l i ze i tw i ththe wei ghts of the edges i nthe gra ph.
-I f therei s n o di rect edge between vertices i a ndj,set
intfib( intn) {
d i st[i ][j]to i nfini ty.
intdp[n+1];//Create a table
-I f therei s a di rect edge between vertices i a ndjw i thwei ght
dp[0]=0;//B ase case
w ,setd i st[i ][j]to w.
dp[1]=1;//B ase case
2.For ea ch vertex'k 'from1toV:
a .For ea ch pa i r of vertices 'i 'a nd'j':
for( inti =2; i<=n; i++) {
i .I f di st[i ][k ]+d i st[k ][j]i s l es s tha n di st[i ][j],
dp[i]= dp[i-1]+dp[i-2];//B uild theresult using stored values
u pdate di st[i ][j]to di st[i ][k ]+d i st[k ][j]
}
3.The fina l 'd i st'm atri x conta i ns the s hortest pathd i sta nces
returndp[n];//F inal result
b etweenallp a i rs of vertices .
}
Backtracking
acktracking is an algorithmic technique for solving problems by
B
exploring all potential solutions and abandoning those that fail to
s atisfy constraints or fail to reach the desired goal (partial
s olutions).
Concepts of Backtracking:
● E xploration:Incrementally builds a solution by tryinga ll
possibilities.
● Constraint Satisfaction:Checks if the current partials olution is
valid; if not, discards it and backtracks.
● Backtrack:Removes the last added element (or undoesthe last
choice) and tries the next option.
Applications of Backtracking:
● N -Queens Problem: Place N queens on an NxN chessboards o
that no two queens attack each other.
● Sudoku Solver:Solve Sudoku puzzles by filling emptycells
following constraints.
● Permutations and Combinations:Generate all permutationsor
combinations of a set.
● Graph Problems: Find paths, such as in the HamiltonianPath
problem.
● Knapsack Problem:Solve optimization problems with
constraints.
Example:
● K napsack Problem:Allocate resources to maximize profitwithin
a weight limit.
● Key Uses:Project management, supply chains, cloudcomputing,
healthcare, etc.
Solution to 4-Queens problem : Algorithm
● Basically, we have to ensure 4 things : F unction SubsetSum(n
ums,target,n):
● No two queens share a column. Create a dp ta bl e of s i ze( n x( ta rget+1) )a ndi ni tia l i zea l l va l ues
● No two queens share a row. to-1
● No two queens share a top-right to left-bottom diagonal.
F unction Sol ve( i ndex,ta rget) :
● No two queens share a top-left to bottom-right diagonal.
I f ta rget==0:ReturnTrue
I f i ndex==0:Return nums [ 0]==ta rget
N-Queens Problem Pseudocode
functions ol veNQueens ( b oa rd,col ) : I f dp[i ndex][ta rget]!=-1:Return dp[i ndex][ta rget]
i fcol >=N:
print( b oa rd) / /Found a s ol ution i ncl ude=Fa l s e
return I f nums [i ndex]<=ta rget:
i ncl ude=S ol ve( i ndex-1,ta rget-n ums [i ndex])
forrow=0to N-1:
i fi s Safe( b oa rd,row,col ) : e xcl ude=S ol ve( i ndex-1,ta rget)
p l a ceQueen( b oa rd,row,col )
s ol veNQueens ( b oa rd,col +1) / /Recurto pl a cenextq ueen p[i ndex][ta rget]=i ncl udeORe xcl ude
d
removeQueen( b oa rd,row,col ) / /B a cktra ck Return dp[i ndex][ta rget]
T ime Complexity:
O(N×N!)
Space Complexity: 2
O(N)
Return Sol ve( n -1,ta rget)
F unction isSafe(vertex,graph,path,position):
# Check if there's an edge from the previous vertexto this vertex
If graph[path[position-1]][vertex]==0:
ReturnFalse
# Check if the vertex is already in the path Numerical
For iinrange(position):
If path[i]==vertex:
ReturnFalse
ReturnTrue
Problem Statement
● Given:
● A set of N cities.
● The cost/distance matrix representing the distances or
costs between every pair of cities.
● Find:
● The shortest route (Hamiltonian circuit) that visits each
city exactly once and returns to the starting city.
Quantum 4.15