针对3个数组的情况,如果需要其他数量的数组,可以插入额外的代码。递归解决方案。
package com.practice.probabilty;
import java.util.ArrayList;
public class CombinationNumber {
public static void main(String[] args) {
int[] arr1 = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] arr2 = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] arr3 = new int[] {0, 2, 4, 6, 8};
int[] arr = arr1.clone();
int r = 3;
int n1 = arr1.length;
int n2 = arr2.length;
int n3 = arr3.length;
int[] count = new int[]{0};
printCombination(arr1, arr2, arr3, arr, n1, n2, n3, r, count);
System.out.println("Total amount of number = " + count[0]);
}
static void combinationUtil_1(int arr1[], int arr2[], int arr3[], int arr[],
int n1, int n2, int n3, int r, int index,
int data[], int i1, int i2, int i3, int[] count) {
if (index == r) {
for (int j = 0; j < r; j++) {
System.out.print(" " + data[j] + " ");
}
System.out.println();
count[0]++;
return;
}
if (i1 >= n1 || i2 >= n2 || i3 >= n3)
return;
if(index == 0)
{
data[index] = arr1[i1];
combinationUtil_1(arr1, arr2, arr3, arr2, n1, n2, n3, r, index + 1, data, i1++, i2, i3, count);
combinationUtil_1(arr1, arr2, arr3, arr2, n1, n2, n3, r, index, data, i1++, i2, i3, count);
}else if(index == 1)
{
data[index] = arr2[i2];
combinationUtil_1(arr1, arr2, arr3, arr3, n1, n2, n3, r, index + 1, data, i1, i2++, i3, count);
combinationUtil_1(arr1, arr2, arr3, arr3, n1, n2, n3, r, index, data, i1, i2++, i3, count);
}
else
{
data[index] = arr3[i3];
combinationUtil_1(arr1, arr2, arr3, arr1, n1, n2, n3, r, index + 1, data, i1, i2, i3++, count);
combinationUtil_1(arr1, arr2, arr3, arr1, n1, n2, n3, r, index, data, i1, i2, i3++, count);
}
}
static void printCombination(int arr1[], int arr2[], int arr3[], int arr[],
int n1, int n2, int n3, int r, int[] count) {
int data[] = new int[r];
combinationUtil_1(arr1, arr2, arr3, arr, n1, n2, n3, r, 0, data, 0, 0, 0, count);
}
}