How to generate all subarrays from an initial array?
Let's consider an array: [1,1,1,1]
.
I would like to generate all possible subarrays (in no particular order).
Expected result:
[1], [1], [1], [1],
[1, 1], [1, 1], [1, 1],
[1, 1, 1], [1, 1, 1],
[1, 1, 1, 1]
My attempt:
List<List<Integer>> list = new ArrayList<>();
generateAllSubArrays(nums, list, 0, 0);
private void generateAllSubArrays(int[] nums, List<List<Integer>> list, int start, int end) {
if (end == nums.length) {
List<Integer> l = new ArrayList<>();
for (int n : nums) {
l.add(n);
}
list.add(l);
} else if (start > end) {
generateAllSubArrays(nums, list, 0, end + 1);
} else {
List<Integer> l = new ArrayList<>();
for (int i = start; i < end; i++) {
l.add(nums[i]);
}
list.add(l);
generateAllSubArrays(nums, list, start + 1, end);
}
}
I'm getting the following result:
[[], [1], [], [1, 1], [1], [], [1, 1, 1], [1, 1], [1], [], [1, 1, 1, 1]]
Issues:
Some empty lists
[]
are present in the result (which is undesired). Unfortunately, I failed to understand why they are here.Some of the expected values are absent, making the result incorrect.
What did I do wrong, and what should I do in order to get the correct computation?
I believe what I tried is using some sort of recursion, increasing space and time complexity. What would be the algorithm with the best space and time complexity?