gpt4 book ai didi

java - 将整数数组推送到 ArrayList

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:17:44 25 4
gpt4 key购买 nike

我被困在将整数数组序列推送到 arraylist 的非常基本的方法中。我正在尝试针对问题 K Combinations of set of Integers 更改多基因润滑剂的解决方案这样我就不会打印它们,而是将它们推送到一个数组列表中。

我的代码:

public class Test {

static ArrayList<String> combinations;
public static void main(String args[]) {
Integer[] a3 = { 1, 2, 3, 4, 5 };
comb(a3, 2);
}
public static void comb(Integer[] items, int k) {
Arrays.sort(items);
combinations = new ArrayList<String>();
ArrayList<String> c1 = new ArrayList<String>();
c1 = kcomb(items, 0, k, new Integer[k]);
System.out.println("from comb");
for (String x : c1) {
System.out.println(x);
}
}
public static ArrayList<String> kcomb(Integer[] items, int n, int k,
Integer[] arr) {
if (k == 0) {
combinations.add(Arrays.toString(arr));
} else {
for (int i = n; i <= items.length - k; i++) {
arr[arr.length - k] = items[i];
kcomb(items, i + 1, k - 1, arr);
}
}
return combinations;
}
}

输出:

from comb
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[2, 3]
[2, 4]
[2, 5]
[3, 4]
[3, 5]
[4, 5]

但是当我如下将 ArrayList 的类型从 String 更改为 Integer[] 时,我得到了冗余输出。

更改代码

public class Test {

static ArrayList<Integer[]> combinations;
public static void main(String args[]) {
Integer[] a3 = { 1, 2, 3, 4, 5 };
comb(a3, 2);
}
public static void comb(Integer[] items, int k) {
Arrays.sort(items);
combinations = new ArrayList<Integer[]>();
ArrayList<Integer[]> c1 = new ArrayList<Integer[]>();
c1 = kcomb(items, 0, k, new Integer[k]);
System.out.println("from comb");
for (Integer[] x : c1) {
System.out.println(Arrays.toString(x));
}
}
public static ArrayList<Integer[]> kcomb(Integer[] items, int n, int k,
Integer[] arr) {
if (k == 0) {
combinations.add(arr);
} else {
for (int i = n; i <= items.length - k; i++) {
arr[arr.length - k] = items[i];
kcomb(items, i + 1, k - 1, arr);
}
}
return combinations;
}
}

输出:

from comb
[4, 5]
[4, 5]
[4, 5]
[4, 5]
[4, 5]
[4, 5]
[4, 5]
[4, 5]
[4, 5]
[4, 5]

谁能帮我指出我做错了什么......

谢谢,萨拉斯

最佳答案

public class Test {

static ArrayList<Integer[]> combinations;
public static void main(String args[]) {
Integer[] a3 = { 1, 2, 3, 4, 5 };
comb(a3, 2);
}
public static void comb(Integer[] items, int k) {
Arrays.sort(items);
combinations = new ArrayList<Integer[]>();
ArrayList<Integer[]> c1 = new ArrayList<Integer[]>();
c1 = kcomb(items, 0, k, new Integer[k]);
System.out.println("from comb");
for (Integer[] x : c1) {
System.out.println(Arrays.toString(x));
}
}
public static ArrayList<Integer[]> kcomb(Integer[] items, int n, int k,
Integer[] arr) {
if (k == 0) {
combinations.add(arr);
} else {
for (int i = n; i <= items.length - k; i++) {
Integer[] arr1 = new Integer[arr.length];
System.arraycopy(arr, 0, arr1, 0, arr.length);
arr1[arr.length - k] = items[i];
kcomb(items, i + 1, k - 1, arr1);
}
}
return combinations;
}
}

关于java - 将整数数组推送到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17257618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com