Handling Base Case in Recursive Function for Generating Combinations in Java
I've looked through the documentation and I'm still confused about I am trying to implement a recursive function in Java to generate all combinations of a given size from an input array. The function seems to work correctly for smaller sizes, but when I try to generate combinations of larger sizes (e.g., size = 4 from an array of 8 elements), I get an ‘ArrayIndexOutOfBoundsException’ error. Here’s my code: ```java import java.util.ArrayList; import java.util.List; public class CombinationGenerator { public static List<List<Integer>> combine(int[] nums, int k) { List<List<Integer>> result = new ArrayList<>(); backtrack(result, new ArrayList<>(), nums, k, 0); return result; } private static void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, int k, int start) { if (tempList.size() == k) { result.add(new ArrayList<>(tempList)); return; } for (int i = start; i < nums.length; i++) { tempList.add(nums[i]); backtrack(result, tempList, nums, k, i + 1); tempList.remove(tempList.size() - 1); } } } ``` When I call ```java int[] nums = {1, 2, 3, 4, 5, 6, 7, 8}; List<List<Integer>> combinations = CombinationGenerator.combine(nums, 4); ``` I expect to get all combinations of 4 elements, but instead, I get this error: ``` Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8 ``` I’ve checked that the array length is indeed 8 and I believe my recursive logic is correct, especially since it works for smaller values of `k`. I suspect it might be related to how I handle the base case or the for loop conditions. Any insights on what might be causing this error or how I could properly fix it? Am I missing any edge cases in my logic? My development environment is Ubuntu.