我正在研究Java中的排列。我的程序应该生成长度为n的数组的所有可能排列,并以r个排列数排列。
下面是一个例子。对于具有以下12个元素的数组
string Mywords[] =("love" ,"guy" ,"cow","hen","dog","antelope","cat" "rat",welcome","thank","you","all");哪里
n=12, r=7选择12个元素中的7个来创建阵列的12个可能的变体。
=>>输出可以是形式(可能的情况)
welcome)
H 113(爱,谢谢,母鸡,鸡,牛,牛,猫)( r)
如何打印所有可能的结果?
发布于 2022-01-08 11:39:23
下面的代码是根据这个问题的答案改编的。
print all possible permutations of r elements in a given integer array of size n in Java
该问题使用整数列表。在下面的代码中,我基本上只将Integer替换为String。
请注意,12个元素列表中的7个元素的排列数接近350万,这将需要时间。因此,在下面的代码中,我从一个五个元素列表中生成三个元素的排列。
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static List<List<String>> choose(List<String> a, int k) {
List<List<String>> allPermutations = new ArrayList<List<String>>();
enumerate(a, a.size(), k, allPermutations);
return allPermutations;
}
// a is the original array
// n is the array size
// k is the number of elements in each permutation
// allPermutations is all different permutations
private static void enumerate(List<String> a,
int n,
int k,
List<List<String>> allPermutations) {
if (k == 0) {
List<String> singlePermutation = new ArrayList<>();
for (int i = n; i < a.size(); i++) {
singlePermutation.add(a.get(i));
}
allPermutations.add(singlePermutation);
return;
}
for (int i = 0; i < n; i++) {
swap(a, i, n - 1);
enumerate(a, n - 1, k - 1, allPermutations);
swap(a, i, n - 1);
}
}
// helper function that swaps a.get(i) and a.get(j)
public static void swap(List<String> a, int i, int j) {
String temp = a.get(i);
a.set(i, a.get(j));
a.set(j, temp);
}
// sample client
public static void main(String[] args) {
// create original array
List<String> elements = new ArrayList<>(List.of("love",
"guy",
"cow",
"hen",
"dog"));
int n = elements.size();
// k is the number of elements of each permutation.
int k = 3;
List<String> a = new ArrayList<>();
for (int i = 0; i < n; i++) {
a.add(elements.get(i));
}
choose(a, k).forEach(list -> System.out.println(list));
}
}运行上述代码将产生以下输出。
[hen, dog, love]
[guy, dog, love]
[cow, dog, love]
[dog, guy, love]
[hen, guy, love]
[cow, guy, love]
[dog, cow, love]
[guy, cow, love]
[hen, cow, love]
[dog, hen, love]
[guy, hen, love]
[cow, hen, love]
[hen, love, guy]
[dog, love, guy]
[cow, love, guy]
[love, dog, guy]
[hen, dog, guy]
[cow, dog, guy]
[love, cow, guy]
[dog, cow, guy]
[hen, cow, guy]
[love, hen, guy]
[dog, hen, guy]
[cow, hen, guy]
[hen, love, cow]
[guy, love, cow]
[dog, love, cow]
[love, guy, cow]
[hen, guy, cow]
[dog, guy, cow]
[love, dog, cow]
[guy, dog, cow]
[hen, dog, cow]
[love, hen, cow]
[guy, hen, cow]
[dog, hen, cow]
[dog, love, hen]
[guy, love, hen]
[cow, love, hen]
[love, guy, hen]
[dog, guy, hen]
[cow, guy, hen]
[love, cow, hen]
[guy, cow, hen]
[dog, cow, hen]
[love, dog, hen]
[guy, dog, hen]
[cow, dog, hen]
[hen, love, dog]
[guy, love, dog]
[cow, love, dog]
[love, guy, dog]
[hen, guy, dog]
[cow, guy, dog]
[love, cow, dog]
[guy, cow, dog]
[hen, cow, dog]
[love, hen, dog]
[guy, hen, dog]
[cow, hen, dog]https://stackoverflow.com/questions/70630186
复制相似问题