【问题标题】:How can I add all available sublists to a new List<List<Integer>>?如何将所有可用的子列表添加到新的 List<List<Integer>>?
【发布时间】:2022-12-01 00:23:46
【问题描述】:

我有一个列表,我正在尝试将列表的子列表添加到新构造的列表<List>,

例如,如果我的 List 是 {2,4,5},我的 List<List> 应该看起来像 {{}{2}{2,4},{2,4,5}},其中 {}{2}{2,4},{2,4,5} 是给定 List 中的所有子列表

这是我的代码:

public static List<List<Integer>> kFactorization(List<Integer> A) {
        List<List<Integer>> c = new ArrayList<>();
        for (int x = A.size(); x <= 0; x++){
                c.add(A.subList(x,0));
            }
        return c;
    }

    public static void main(String[] args) {
        System.out.println(kFactorization(List.of(2, 3, 4, 5)));
    }

但是,当我运行它时,我只是得到一个 {},我需要对我的代码进行哪些更改?

【问题讨论】:

  • what changes do I need to make - 学习数学并学习编码。
  • 看看操作是如何工作的。 int x = A.size(); x &lt;= 0; x++ 在这种情况下条件 x &lt;= 0 永远不会达到
  • @K.Nicholas 是的,我正在学习编码,您还认为我在问题中提供的代码来自哪里?如果您决定发表评论/回答,那么至少提供一些与该问题相关的信息,否则请转到其他问题。
  • @Droid - 好的。还要学习使用打印语句进行调试。
  • @Droid,如果问题已关闭,请不要在新问题中问同样的问题。相反,编辑已关闭的问题来解决问题。

标签: java list integer sublist


【解决方案1】:

既然你正在学习编程,我不想给你写代码。相反,我会尝试让您对任务有一些了解,以便您可以制定自己的解决方案。

让我们看看你的例子 [2, 4, 5]

你想得到 [], [2], [2, 4], [2, 4, 5]

或者换句话说,如果您从索引和子列表的角度考虑,结果是: [sublist(0, 0), sublist(0, 1) ... sublist (0, n)] 其中n 是给定列表的长度,在我们的示例中为 3。

现在你应该看看List.subList()方法https://docs.oracle.com/javase/8/docs/api/java/util/List.html#subList-int-int-的文档

现在你准备好写一个特定的算法

define List<List<T> result
for index in given list from 0 to list.size {
  add to result sublist of given list from 0 to index
}
return result

【讨论】:

    猜你喜欢
    • 2014-05-13
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多