Interview question: backtracking algorithm recursively searches to find all combinations
import java.util.ArrayList; import java.util.List; /** *Find all combinations whose sum is 100 in a non repeated random array of 1-100 [1,2,3,7,9,88,94,95,97,99], such as [1,99], [2,3,95], [1,2,3,94], [xxx, xx, xx, xxxx] */ public class CombinationSum { public static void main(String[] args) { int[] nums = {1, 2, 3, 7, 9, 88, 94, 95, 97, 99}; int target = 100; List<List<Integer>> combinations = findCombinations(nums, target); System.out.println(combinations); } public static List<List<Integer>> findCombinations(int[] nums, int target) { List<List<Integer>> combinations = new ArrayList<>(); backtrack(combinations, new ArrayList<>(), nums, target, 0); return combinations; } /** *In this code, the findCombinations method receives an integer array number and the target and target, and returns a list containing all the combinations of and target. *We use the backtracking algorithm to perform recursive search, and construct the combination by continuously selecting and deselecting elements in the array. In each step, we check whether the current sum is equal to the target sum, *If yes, add the current combination to the result list; If the sum is less than the target sum, continue to search down; If the sum is greater than the target sum, it will be backtracked to the previous level. * *@ param combinations *@ param currentCombination *@ param num The array to traverse *@ param remaining *@ param start Start indexing */ private static void backtrack(List<List<Integer>> combinations, List<Integer> currentCombination, int[] nums, int remaining, int start) { if (remaining == 0) { combinations.add(new ArrayList<>(currentCombination)); return; } if (remaining < 0) { return; } for (int i = start; i < nums.length; i++) { if (i > start && nums[i] == nums[i - 1]) { continue; // Skip duplicates } currentCombination.add(nums[i]); backtrack(combinations, currentCombination, nums, remaining - nums[i], i + 1); currentCombination.remove(currentCombination.size() - 1); } } }