【发布时间】:2018-06-24 01:42:03
【问题描述】:
我的目标是在具有固定预定义长度的 ArrayList 中找到所有可能的项目组合。例如,如果我的 ArrayList 称为 arr 并包含 <1, 2, 3>,那么预定义大小 r = 2 的所需输出将是:
<1,2>
<1,3>
<2,3>
这是我找到的打印所需输出的代码。我的问题是我需要定义一个返回值类型 ArrayList 来保存方法的输出。此外,我的输入类型也是ArrayList<Integer>,而不是数组,这对我来说变得更加复杂,因为我首先需要将值转换为原始类型 int。
import java.io.*;
class Permutation {
/* arr[] ---> Input Array
data[] ---> Temporary array to store current combination
start & end ---> Staring and Ending indexes in arr[]
index ---> Current index in data[]
r ---> Size of a combination to be printed */
static void combinationUtil(int arr[], int data[], int start,
int end, int index, int r)
{
// Current combination is ready to be printed, print it
if (index == r)
{
for (int j=0; j<r; j++)
System.out.print(data[j]+" ");
System.out.println("");
return;
}
// replace index with all possible elements. The condition
// "end-i+1 >= r-index" makes sure that including one element
// at index will make a combination with remaining elements
// at remaining positions
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
static void printCombination(int arr[], int n, int r)
{
// A temporary array to store all combination one by one
int data[]=new int[r];
// Print all combination using temprary array 'data[]'
combinationUtil(arr, data, 0, n-1, 0, r);
}
/*Driver function to check for above function*/
public static void main (String[] args) {
int arr[] = {1, 2, 3, 4, 5};
int r = 3;
int n = arr.length;
printCombination(arr, n, r);
}
}
/* This code is contributed by Devesh Agrawal */
【问题讨论】:
标签: java arraylist combinations