[英]Java- How to find the permutation of all values in a 1 dimensional array and store them in a 2 dimensional array
I want to create a method in which, when given a 1 dimensional array, it'll find all permutations of the values in that array and make it into a 2 dimensional array. 我想创建一个方法,当给定一个1维数组时,它将找到该数组中值的所有排列并将其变成2维数组。 I found some algorithms online which finds all the permutations but only prints the values out in the form of a 2d array( example ), but I couldn't quite modify the code to store the output into a single 2d array.
我在线上找到了一些算法,该算法可以找到所有排列,但是只能以2d数组( 示例 )的形式打印出值,但是我不能完全修改将输出存储到单个2d数组中的代码。 Any help would be appreciated, thank you.
任何帮助,将不胜感激,谢谢。
Here's how I would do it - adapted from the link in your question: 这是我的处理方式-根据您问题中的链接改编而成:
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
// Java program to calculate all permutations using
// Heap's algorithm
class HeapAlgo
{
List<int[]> heapPermutation(int a[]) {
LinkedList<int[]> list = new LinkedList<int[]>();
heapPermutation(a, a.length, a.length, list);
return list;
}
//Generating permutation using Heap Algorithm
void heapPermutation(int a[], int size, int n, List<int[]> list)
{
// if size becomes 1 then adds the obtained
// permutation to the list
if (size == 1)
list.add(a.clone());
for (int i=0; i<size; i++)
{
heapPermutation(a, size-1, n, list);
// if size is odd, swap first and last
// element
if (size % 2 == 1)
{
int temp = a[0];
a[0] = a[size-1];
a[size-1] = temp;
}
// If size is even, swap ith and last
// element
else
{
int temp = a[i];
a[i] = a[size-1];
a[size-1] = temp;
}
}
}
// Driver code
public static void main(String args[])
{
HeapAlgo obj = new HeapAlgo();
int a[] = {1,2,3};
List<int[]> list = obj.heapPermutation(a);
for(Iterator<int[]> i = list.iterator(); i.hasNext();) {
int[] array = i.next();
for(int j = 0; j < array.length; j++) {
System.out.print(array[j] + " ");
}
System.out.println();
}
}
}
// Based on code contributed by Amit Khandelwal.
Another approach would be to create an array of int[]
arrays. 另一种方法是创建一个
int[]
数组的数组。 The length would be the factorial of the length of a
. 该长度将是
a
的长度的阶乘。 You could create a stack class that tracks the lowest empty index to add the next permutation to. 您可以创建一个跟踪最低空索引的堆栈类,以向其添加下一个排列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.