Which of the following best explains why greedy algorithms sometimes fail to find the best solution?
Think about how greedy algorithms choose their next step.
Greedy algorithms pick the best immediate choice without looking ahead, so they can miss better overall solutions.
What is the output of the following Python code that uses backtracking to find subsets summing to 5?
def backtrack(nums, target, start, path, res): if target == 0: res.append(path[:]) return if target < 0: return for i in range(start, len(nums)): path.append(nums[i]) backtrack(nums, target - nums[i], i + 1, path, res) path.pop() result = [] backtrack([1, 2, 3, 4], 5, 0, [], result) print(result)
Check which combinations of numbers add up exactly to 5 without reuse.
The code finds all unique subsets of [1,2,3,4] that sum to 5. These are [1,4] and [2,3].
Consider the coin denominations [1, 3, 4] and the amount 6. The greedy algorithm picks the largest coin first. What is the output of the code below?
def greedy_coin_change(coins, amount): coins.sort(reverse=True) count = 0 for coin in coins: while amount >= coin: amount -= coin count += 1 return count print(greedy_coin_change([1, 3, 4], 6))
Try to see which coins the greedy picks first and how many coins it uses.
The greedy picks 4 first, then two 1s, totaling 3 coins. But the optimal is two coins: 3 + 3.
What is the output of the code that counts paths from top-left to bottom-right in a 2x2 grid moving only right or down?
def count_paths(r, c, max_r, max_c): if r == max_r and c == max_c: return 1 if r > max_r or c > max_c: return 0 return count_paths(r + 1, c, max_r, max_c) + count_paths(r, c + 1, max_r, max_c) print(count_paths(0, 0, 1, 1))
Count all ways to move right or down from (0,0) to (1,1).
There are two paths: right then down, or down then right.
Why can't a greedy algorithm solve the N-Queens problem efficiently?
Think about how placing queens affects the board and future choices.
Greedy placement can cause conflicts later, so backtracking tries different placements to find all solutions.
