Generate all subarrays of an array

ghz 10months ago ⋅ 153 views

To generate all subarrays of an array, you can use nested loops to iterate over all possible start and end indices of subarrays. Here's a Java implementation:

import java.util.ArrayList;
import java.util.List;

public class Subarrays {

    public static List<List<Integer>> generateSubarrays(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();

        for (int start = 0; start < nums.length; start++) {
            for (int end = start; end < nums.length; end++) {
                List<Integer> subarray = new ArrayList<>();
                for (int i = start; i <= end; i++) {
                    subarray.add(nums[i]);
                }
                result.add(subarray);
            }
        }

        return result;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        List<List<Integer>> subarrays = generateSubarrays(nums);

        System.out.println("All subarrays:");
        for (List<Integer> subarray : subarrays) {
            System.out.println(subarray);
        }
    }
}

In this implementation:

  • We use nested loops to iterate over all possible start and end indices of subarrays.
  • For each combination of start and end indices, we create a subarray by iterating from the start index to the end index and add the elements to a list.
  • We add each subarray to the result list.
  • We return the list containing all subarrays.
  • We test the implementation with an example array and print all generated subarrays.