Question
Recursively generate all ways in which an array can be split up into a sequence of nonempty sublists. For example, if you are given the
Recursively generate all ways in which an array can be split up into a sequence of nonempty sublists. For example, if you are given the array [1, 7, 2, 9], return the following lists of lists: [[1], [7], [2], [9]], [[1, 7], [2], [9]], [[1], [7, 2], [9]], [[1, 7, 2], [9]], [[1], [7], [2, 9]], [[1, 7], [2, 9]], [[1], [7, 2, 9]], [[1, 7, 2, 9]] Hint: First generate all sublists of the list with the last element removed. The last element can either be a subsequence of length 1, or it can be added to the last subsequence. The skeleton of a class called SubArrayGenerator is provided to you. Complete the method
/** * * */ public class SubarrayGenerator { public static void main(String[] args) { int[] listOne = {1,2}; System.out.println(generateSubarrays(listOne)); System.out.println("Expected: [[1], [2]], [[1, 2]]"); int[] listTwo = {7,3,5}; System.out.println(generateSubarrays(listTwo)); System.out.println("Expected: [[7], [3], [5]],[[7, 3], [5]], [[7], [3, 5]], [[7, 3, 5]]"); int[] listThree = {1,7,2,9}; System.out.println(generateSubarrays(listThree)); System.out.println("Expected: [[1], [7], [2], [9]],[[1, 7], [2], [9]],[[1], [7, 2], [9]],[[1, 7, 2], [9]], [[1], [7], [2, 9]],[[1, 7], [2], [9]], [[1], [7, 2, 9]], [[1, 7, 2, 9]]"); } /** * A helper method for a method that recursively generate all ways * in which an array list can be split up into a sequence of * nonempty sublists. * @param sequence an array of integers * @return a string representing all non-empty sub-lists */ public static String generateSubarrays(int[] sequence) { //Complete this method; add as many helper methods //as needed. } }
Expected output for an array of [1, 7, 2, 9]: [[1], [7], [2], [9]], [[1, 7], [2], [9]], [[1], [7, 2], [9]], [[1, 7, 2], [9]], [[1], [7], [2, 9]], [[1, 7], [2, 9]], [[1], [7, 2, 9]], [[1, 7, 2, 9]]
MUST USE RECURSION!!
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started