using System; using System.Collections.Generic; class Program { static void Backtrack(int[] nums, int target, int start, List<int> current, List<List<int>> result) { if (target == 0) { result.Add(new List<int>(current)); return; } if (target < 0) return; for (int i = start; i < nums.Length; i++) { current.Add(nums[i]); Backtrack(nums, target - nums[i], i + 1, current, result); current.RemoveAt(current.Count - 1); } } static void Main() { int[] nums = {1, 2, 3, 4, 5}; int target = 5; List<List<int>> result = new List<List<int>>(); Backtrack(nums, target, 0, new List<int>(), result); foreach (var subset in result) { Console.WriteLine(string.Join(", ", subset)); } } }
The backtracking code finds all subsets of the array {1,2,3,4,5} that sum to 5. It explores combinations without repetition and prints each valid subset.
The valid subsets are: [1,4], [2,3], and [5].
Greedy algorithms pick the best immediate choice, like the largest number, but this can miss valid subsets that require smaller numbers combined.
Subset sum needs to explore all combinations, which greedy does not do.
using System; class Program { static int GreedyChange(int amount, int[] coins) { int count = 0; foreach (int coin in coins) { while (amount >= coin) { amount -= coin; count++; } } if (amount != 0) throw new Exception("Cannot make exact change"); return count; } static void Main() { int[] coins = {4, 3, 1}; int amount = 6; Console.WriteLine(GreedyChange(amount, coins)); } }
The greedy algorithm picks 4 first, then two 1s, totaling 3 coins.
But the optimal solution is two coins: 3 + 3.
Greedy fails to find the minimum coins here.
The N-Queens problem requires exploring all possible placements and backtracking when conflicts occur.
Greedy placing queens in the first safe spot may fail to find a solution.
The Hamiltonian Path problem requires checking many possible vertex orders to find a path visiting all vertices once.
Greedy algorithms pick edges locally and may miss valid paths.
