【问题标题】:How to find all contiguous sub array combinations of an array and print it如何找到数组的所有连续子数组组合并打印它
【发布时间】:2021-06-05 13:32:00
【问题描述】:

我需要编写一个程序以特定格式打印数组的所有子数组。

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,2,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);
}

这段代码给出了所有可能的子数组,但不是所有可以从数组形成的传染性子数组组合。

【问题讨论】:

    标签: java arrays dynamic-programming sub-array


    【解决方案1】:

    如果没有递归,这有点困难。即使是递归也很难,因为你必须在递归方法中循环,这很不寻常。

    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}, 0, "");
      }
    }
    

    这个输出:

    (1),(2),(3),(4)
    (1),(2),(3,4)
    (1),(2,3),(4)
    (1),(2,3,4)
    (1,2),(3),(4)
    (1,2),(3,4)
    (1,2,3),(4)
    (1,2,3,4)
    

    【讨论】:

      【解决方案2】:

      解决方案符合问题的要求,但我想警告这些并非都是子集组合

      缺少的组合是:

      (4,2),(3,1)
      (4,1),(2,3)
      (2),(1,3,4)
      (3),(1,2,4)
      (2),{4),(1,3)
      (1),(3),(2,4)
      (2),(3),(1,4)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-24
        • 2020-12-02
        • 1970-01-01
        • 2016-09-02
        • 2020-09-18
        • 1970-01-01
        • 1970-01-01
        • 2016-10-31
        相关资源
        最近更新 更多