如我的代码所示,如果int x = 100,int y = 50,我必须编写50 for循环来获得结果。如何在不用Java手动输入的情况下使用递归来运行n嵌套循环?
public static void main(String[] args) {
// create a blank arrayList to store raw data
ArrayList < Integer > originalData = new ArrayList < > ();
// create a blank arrayList to store all combinations
ArrayList < ArrayList < Integer >> allCombinations = new ArrayList < > ();
// the length of the arraylist we just created.
// suppose it's 4 now.
int x = 4;
// generate elements
for (int i = 0; i < x; i++) {
originalData.add(i);
}
// how many elements we need in each combination.
// suppoer it's 3 now
int y = 3;
// the number of for-loop is y
for (int i = 0; i < originalData.size(); i++) {
for (int j = 0; j < originalData.size(); j++) {
for (int k = 0; k < originalData.size(); k++) {
// create a new arrayList to store all elements in a single combination
ArrayList < Integer > singleItem = new ArrayList < > ();
singleItem.add(originalData.get(i));
singleItem.add(originalData.get(j));
singleItem.add(originalData.get(k));
// store all combinations to an arraylist
allCombinations.add(singleItem);
}
}
}
System.out.println(allCombinations);
}