为什么这里的combArray是空的而下面
这里明明给combArray赋值了呀
源代码如下:
import java.util.ArrayList;
import java.util.List;
public class FindCombination {
private int begin, end;// 组合最小、大长度
// number长度的组合集合
private List<CombNode> combArray = new ArrayList<CombNode>();
// begin-end长度的组合集合
private List<List<CombNode>> combBalls = new ArrayList<List<CombNode>>();
public FindCombination(CombNode[] array, int begin, int end) {//初始器
this.begin = begin;
this.end = end;
if (array == null || array.length == 0 || begin > end) {
System.out
.println("wrong,the reason maybe is :\"array==null\" or \"array.length == 0\" or \"begin>end\"");
return;
}
List<CombNode> list = new ArrayList<CombNode>();
for (int length = begin; length <= end; length++) {
combination(array, 0, length, list);
combBalls.add(combArray);
System.out.println("#######");
System.out.print("初始器里combArray:");
for (int i = 0; i < combArray.size(); i++) {
System.out.print(combArray.get(i).getValue() + " ");
}
System.out.println();
System.out.println("#######");
combArray.clear();
}
}
//递归选取元素
private void combination(CombNode[] array, int begin, int length,
List<CombNode> list) {
if (length == 0) {
combArray = list;
for (int i = 0; i < combArray.size(); i++) {
System.out.print(combArray.get(i).getValue() + " ");
}
System.out.println();
return;
}
if (begin == array.length) {
return;
}
list.add(array[begin]);
combination(array, begin + 1, length - 1, list);
list.remove(array[begin]);
combination(array, begin + 1, length, list);
}
public List<CombNode> getXLengthCombination(int length) {//获取x长度的所有组合
if (length < begin || length > end) {
System.out
.println("wrong,the length must be greater than begin and less than end at the same time");
return null;
}
return combBalls.get(length);
}
public void printCombination() {// 打印所有组合
for (int i = 0; i < combBalls.size(); i++) {
for (int j = 0; j < combBalls.get(i).size(); j++) {
System.out.print(combBalls.get(i).get(j).getValue() + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
String[] array = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
// int[] array={1,2,3,4,5,6,7,8,9,10};
CombNode[] cn = new CombNode[10];
for (int i = 0; i < array.length; i++) {
cn[i] = new CombNode(array[i], true);
}
System.out.println("\n***********");
FindCombination fc = new FindCombination(cn, 1, 2);
System.out.println("***********");
System.out.println("通过方法打印");
fc.printCombination();
}
}
按照自己的节奏前行
相关分类