[英]How do i optimize below code so that it can accept any array size and give me the result
The below code displays the subarrays of the given array. 下面的代码显示给定数组的子数组。 But if i increase array size by one the below code fails to display all the subarrays, to make it successfully display all the arrays i need to add one more for loop. 但是,如果我将数组大小增加1,则以下代码无法显示所有子数组,要使其成功显示所有数组,我需要再添加一个for循环。 So how can i optmize code so that it display all the subarrays dynamically by not depending on the array size. 因此,我如何优化代码,使其不依赖于数组大小而动态显示所有子数组。
public class Subarrays {
public static void main(String[] args)
{
int[] arr=new int[] {1,-2,4,-5,1};
int count=0;
for(int i=0; i<arr.length; i++) {
System.out.println("["+arr[i]+"]");
for(int j=0; j<arr.length-(i+1); j++) {
}
}
for(int i=0; i<arr.length-1; i++) {
System.out.println("["+arr[i]+","+arr[i+1]+"]");
}
for(int i=0; i<arr.length-2;i++)
{
System.out.println("["+arr[i]+","+arr[i+1]+","+arr[i+2]+"]");
}
for(int i=0; i<arr.length-3; i++) {
System.out.println("["+arr[i]+","+arr[i+1]+","+arr[i+2]+","+arr[i+3]+"]");
}
for(int i=0; i<arr.length-4; i++) {
System.out.println("["+arr[i]+","+arr[i+1]+","+arr[i+2]+","+arr[i+3]+","+arr[i+4]+"]");
}
}
}
public static void printAllSubArrays(int[] arr) {
for (int len = 1; len <= arr.length; len++) {
for (int from = 0; from + len <= arr.length; from++) {
System.out.print('[');
for (int i = from; i < from + len; i++) {
if (i != from)
System.out.print(',');
System.out.print(arr[i]);
}
System.out.println(']');
}
}
}
Demo: 演示:
printAllSubArrays(new int[] { 1, -2, 4, -5, 1 });
Output: 输出:
[1]
[-2]
[4]
[-5]
[1]
[1, -2]
[-2, 4]
[4, -5]
[-5, 1]
[1, -2, 4]
[-2, 4, -5]
[4, -5, 1]
[1, -2, 4, -5]
[-2, 4, -5, 1]
[1, -2, 4, -5, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.