在Java中查找一个给定数组的所有子数组
数组是一种线性数据结构,其中的元素被存储在连续的内存位置。
根据问题陈述,我们必须找到一个给定数组的所有子数组。子数组是一个数组的一部分或一个部分。当我们谈论一个数组的所有子数时,我们谈论的是可以使用该数组的所有元素而不重复的组合总数。
让我们探讨一下这篇文章,看看如何通过使用Java编程语言来实现。
向你展示一些实例
实例一
假设我们有以下数组
[10, 2, 3, -5, 99, 12, 0, -1]
这个数组的子数组将是
10
10 2
10 2 3
10 2 3 -5
10 2 3 -5 99
10 2 3 -5 99 12
10 2 3 -5 99 12 0
10 2 3 -5 99 12 0 -1
2
2 3
2 3 -5
2 3 -5 99
2 3 -5 99 12
2 3 -5 99 12 0
2 3 -5 99 12 0 -1
3
3 -5
3 -5 99
3 -5 99 12
3 -5 99 12 0
3 -5 99 12 0 -1
-5
-5 99
-5 99 12
-5 99 12 0
-5 99 12 0 -1
99
99 12
99 12 0
99 12 0 -1
12
12 0
12 0 -1
0
0 -1
-1
实例2
假设我们有以下数组
[55,10,29,74]
这个数组的子数组将是
55
55 10
55 10 29
55 10 29 74
10
10 29
10 29 74
29
29 74
74
算法
算法-1
- 第1步 – 存储完数组后,运行一个从0到n的for循环,这将标志着我们的主数组的起点。
 - 
第2步– 运行另一个for循环,从第一个迭代器运行到主数组的结束点。
 - 
第3步 – 现在运行另一个循环,遍历两个迭代器之间的元素。
 - 
第4步 – 按顺序打印这些元素。
 
算法-2
- 
第1步 – 在存储数组后,检查我们是否已经到达终点,然后走出函数。
 - 
第2步 – 如果开始索引大于结束索引,那么从0到end+1调用函数本身。
 - 
第3 步 – 否则在for循环内打印索引之间的数组元素,并从start+1到end再次调用该函数。
 - 
第4步 – 退出。
 
语法
要获得一个数组的长度(该数组中的元素数),数组有一个内置的属性,即 长度
下面是它的语法
array.length
其中,’array’指的是数组引用。
你可以使用Arrays.sort()方法将数组按升序排序。
Arrays.sort(array_name);
多种方法
我们已经提供了不同方法的解决方案。
- 通过使用for循环
 - 
通过使用递归
 
让我们逐一看看这个程序和它的输出。
方法一:通过使用for循环
在这种方法中,我们将使用三个for循环来寻找一个数组的子数。第一个循环标记子数的开始,第二个循环标记子数的结束,而第三个循环则打印子数。
例子
import java.io.*;
public class Main {
   public static void main(String[] args) {
      // The array elements
      int arr[] = { 10, 2, 3, 99, 12, 0 };
      System.out.println("The subarrays are-");
      // For loop for start index
      for (int i = 0; i < arr.length; i++)
      // For loop for end index
      for (int j = i; j < arr.length; j++) {
         // For loop to print subarray elements
         for (int k = i; k <=j; k++)
            System.out.print(arr[k] + " ");
            System.out.println("");
      }
   }
}
输出
The subarrays are-
10 
10 2 
10 2 3 
10 2 3 99 
10 2 3 99 12 
10 2 3 99 12 0 
2 
2 3 
2 3 99 
2 3 99 12 
2 3 99 12 0 
3 3 99 3 99 12 3 99 12 0 
99 
99 12 
99 12 0 
12 12 0 
0 
方法-2:通过使用递归
在这种方法中,我们使用递归找到所有的子数。
例子
import java.io.*;
public class Main {
   //main method
   public static void main(String[] args) {
      // The array elements
      int arr[] = { 10, 2, 3};
      System.out.println("The subarrays are-");
      // Calling the recursive function
      printSubArrays(arr, 0, 0);
   }
   // Recursive FUnction to Find all the subarrays
   static void printSubArrays(int[] arr, int head, int tail) {
      // Exits the function if we have reached the end
      if (tail == arr.length)
         return;
      // Increases the first index and calls itself
      else if (head > tail)
         printSubArrays(arr, 0, tail + 1);
      // Print the subarray and then increases the first element index
      else {
         for (int i = head; i < tail; i++)
            System.out.print(arr[i] + " ");
         System.out.println(arr[tail]);
         printSubArrays(arr, head + 1, tail);
      }
      return;
   }
}
输出
The subarrays are-
10
10 2
2
10 2 3
2 3
3
在这篇文章中,我们探讨了如何通过使用Java编程语言找到一个给定数组的所有子数。
极客教程