java打印没有元素邻接的所有子序列数组
在下文中,我可以打印所有子序列数组,但请有人帮助打印没有相邻元素的所有子序列
`package test;
import java.util.ArrayList;
import java.util.List;
public class Test1 {
public static List<List<Integer>> combinations(int[] arr) {
List<List<Integer>> combinations = new ArrayList<List<Integer>>();
List<Integer> total;
for (int i = 0; i < arr.length; i++) {
int k = combinations.size();
for (int j = 0; j < k; j++) {
// if ((i + 1 < arr.length)) {
total = new ArrayList<Integer>(combinations.get(j));
total.add(new Integer(arr[i]));
combinations.add(total);
// }
}
total = new ArrayList<Integer>();
total.add(new Integer(arr[i]));
combinations.add(total);
}
System.out.println(combinations);
return combinations;
}
public static void main(String args[]) {
int arr[] = { 1, 2, 3 };
combinations(arr);
}
}`
输出:-[[1]、[1,2]、[2]、[1,3]、[1,2,3]、[2,3]、[3]]
预期产出:-[1],[2],[1,3],[3]]
# 1 楼答案
生成组合:
驱动程序代码:
输出:
算法:
让我们把数组看作{1,2,3,4,5,6}
换句话说,这意味着我将从开始迭代所有组合,并在我可以生成的总组合-1处停止(其中
-1
本身不包括)为了更清晰,让我们看一下这些组合。假设前两种组合已经存在
3
我们从一开始就想4
,我们将有所有组合摆在我们面前:[2]
然后停下来,组合如下: