递归方法非常简单。伪代码(不确定如何处理Java静态/非静态等):
编辑:制作
if (m < 0)
public static void cartesianPower(int arr[], int tmpArr[], int n, int m){
if (m < 0)
System.out.println(Arrays.toString(tmpArr));
else
for (int i = 0; i < n; i++) {
tmpArr[m] = arr[i];
cartesianPower(arr, tmpArr, n, m - 1);
}
}
Working
def cartesianPower(arr, tmpArr, n, m):
if (m < 0):
print(tmpArr)
else:
for i in range(n):
tmpArr[m] = arr[i]
cartesianPower(arr, tmpArr, n, m - 1)
arr = [0,1,2]
tmpArr = [0,0,0]
cartesianPower(arr, tmpArr, len(arr), len(arr) - 1)
Version with lexicographic ordering