【问题标题】:how to print subsets of an array with a specific length in java如何在java中打印具有特定长度的数组的子集
【发布时间】:2015-11-06 07:26:17
【问题描述】:

我想打印数组长度为 n 和子集长度为 k 的数组的子集。 例如,您有 {1,2,3} 并且您必须在不同的行中打印 {1,2} {1,3} {2,3} 并排序。(另外您必须在之前打印 {1,2} {1,3}) 我在网上搜索,但他们使用的是不允许的数组列表。 如果有人请帮助解决这个问题,我将不胜感激。

【问题讨论】:

  • 请给我们看一些代码,即到目前为止你做了什么,你在哪里卡住了。 StackOverflow 不是要回答一般问题或免费进行编码,但社区会很乐意帮助您解决特定问题。谢谢,欢迎!
  • 输入数组是否已排序?输入数组可以包含重复的条目吗?
  • 数组没有重复的条目。数组没有排序。
  • 我什至不知道从哪里开始。我还没有写任何代码。

标签: java arrays subset


【解决方案1】:

在 main 中,我们对数组进行排序并调用称为 loopy_loop 的递归方法。如果这对您来说是新标准,您也可以在此处要求自定义排序。

public static void main(String[] args) {
    int[] source = {0,8,2,3,1,9,5,6,4,7};
    int k = 3, n = 10;
    int[] destination = new int[k];

    // first the sorting
    Arrays.sort(source);


    for (int i = 0; i < n; i++)
        System.out.print(source[i] + " ");
    System.out.println();

    if (k > 0)
        loopy_loop(source, destination, 0, 0);

}

这是一个递归函数。级别遵循 (int)k 的值,并确定要在 destination[] 中填充的位置以及递归的“深度”。

public static void loopy_loop(int[] source, int[] destination, int level, int startIndex) {

    for (int i = startIndex; i < source.length - destination.length + level + 1; i++) {
        destination[level] = source[i];
        if (level == destination.length - 1)
        {
            String rez = String.valueOf(destination[0]);
            for (int j = 1; j < destination.length; j++)
                rez += ", " + destination[j];
            System.out.println("{"+ rez +"}");
        }
        else
            loopy_loop(source, destination, level + 1, i + 1);
    }

}

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 2021-12-13
    • 2019-07-13
    • 1970-01-01
    • 2020-07-23
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多