我被困在非常基本的将整数数组序列推向数组列表的方式。 我正在尝试改变这个问题的polygenelubricants的解决方案,而不是打印它们,我将它们推到一个数组列表中。将整数数组推送到ArrayList
我的代码:
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中的类型整数[]如下,我正在冗余输出。
改变的代码
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]
人可以帮我指出我在做什么错?
感谢, 萨拉特
确定它的'ArrayList'不'ArrayList ' –
codeMan
@codeMan,因为我们得到a3中的整数组合,它应该是ArrayList。我试图在arraylist中存储的是多组组合。 –