Dsa 05
Dsa 05
Characteristics:
● Optimal substructure
● Overlapping subproblems
def fibonacci(n):
fib = [0, 1]
fib.append(fib[i-1] + fib[i-2])
return fib[n]
n = len(weights)
if weights[i-1] <= w:
else:
dp[i][w] = dp[i-1][w]
return dp[n][W]
Greedy Algorithms
Greedy algorithms build a solution step by step by choosing the locally optimal choice.
def activity_selection(activities):
activities.sort(key=lambda x: x[1])
selected = [activities[0]]
selected.append(activities[i])
return selected
Backtracking
Backtracking involves exploring all possible solutions and retreating when a solution fails.
def solve_n_queens(n):
board = [-1] * n
for i in range(row):
return False
return True
def place_queen(row):
if row == n:
return [board[:]]
solutions = []
if is_safe(row, col):
board[row] = col
solutions += place_queen(row + 1)
return solutions
return place_queen(0)
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i=j=k=0
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
Conclusion
Advanced algorithms offer efficient solutions for complex problems. Mastering these techniques
is crucial for competitive programming and real-world problem-solving.