1 回答

TA貢獻1868條經驗 獲得超4個贊
從技術上講,排列意味著某些元素的重新排序,例如,[3,1,2]
是 的排列[1,2,3]
。您所要求的相當于迭代笛卡爾積,因此 Python 函數被命名為product
。
正如您正確地注意到的,遞歸是這里的方法。這是因為生成 的所有序列[5,3,4,6]
需要生成[3,4,6]
以 0 開頭的所有序列,然后再次以 1 開頭,依此類推,直到 5。
import java.util.Arrays;
public class CartesianProduct {
? ? public static void main(String[] args) {
? ? ? ? printAll(5, 3, 4, 6);
? ? }
? ? public static void printAll(int... maxes) {
? ? ? ? int[] current = new int[maxes.length];
? ? ? ? printAll(maxes, current, 0);
? ? }
? ? private static void printAll(int[] maxes, int[] current, int i) {
? ? ? ? if(i == current.length) {
? ? ? ? ? ? System.out.println(Arrays.toString(current));
? ? ? ? } else {
? ? ? ? ? ? int max = maxes[i];
? ? ? ? ? ? for(int j = 0; j <= max; ++j) {
? ? ? ? ? ? ? ? current[i] = j;
? ? ? ? ? ? ? ? printAll(maxes, current, i+1);
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
變量i是我們當前選擇值的位置的索引,變量j是該位置的當前值,數組current保存當前序列。遞歸的基本情況是在所有位置都選擇了值,然后我們打印。
添加回答
舉報