如何解决如何查找数组的所有连续子数组组合并打印它
我需要编写一个程序,以特定格式打印数组的所有子数组。
Example-
I/o:
n = 3
A = (1,2,3) where n is the size of the array and A is the array itself.
O/p:
(1),(2),(3)
(1),(2,3)
(1,2),(3)
(1,3)
我能够使用两个循环获取所有子数组,但无法按此特定顺序生成输出。我正在使用 Java 进行编码。 我的代码如下:- a[]→n 个元素的整数数组
for(int i=0;i<a.length;i++){
String s = "";
for(int j=i;j<a.length;j++){
s = s + a[j] + " ";
System.out.println(s);
}
这段代码给出了所有可能的子数组,但不是所有可以从数组形成的传染性子数组组合。
解决方法
如果没有递归,这有点困难。即使是递归也很难,因为你必须在递归方法内部循环,这很不寻常。
class Main {
static void printGroups(int[] a,int start,String output) {
output += "(" + a[start];
for (int i = start + 1; i < a.length; i++) {
printGroups(a,i,output + "),");
output += "," + a[i];
}
System.out.println(output + ")");
}
public static void main(String[] args) {
printGroups(new int[]{1,2,3,4},"");
}
}
输出:
(1),(2),(3),(4)
(1),(3,4)
(1),(2,3),4)
(1,2),(4)
(1,4)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。