[英]Creating permutations of n size
I'm currently trying to make a method that will take a string and a number, and will then print all permutations of the string that are the size of the number.我目前正在尝试制作一种方法,该方法将接受一个字符串和一个数字,然后将打印该数字大小的字符串的所有排列。 For example, permutation("barn", 3) would print "bar", "rab", "arn", and so forth.
例如, permutation("barn", 3) 将打印 "bar"、"rab"、"arn" 等等。 So far, I have this method which correctly print all permutations of a string:
到目前为止,我有这个方法可以正确打印字符串的所有排列:
public static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
Now I just need to implement the function that limits the size of each permutation, but I'm lost on what to do.现在我只需要实现限制每个排列大小的函数,但我不知道该怎么做。 Any help would be appreciated!
任何帮助,将不胜感激!
You just have to add a length parameter to the method, and print the prefix once it reaches that length:您只需要向该方法添加一个长度参数,并在达到该长度后打印前缀:
public static void permutation(String prefix, String str, int len) {
int n = str.length();
if (prefix.length() == len) {
System.out.println(prefix);
} else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n), len);
}
}
Now, if you execute现在,如果你执行
permutation("","barn",3);
you get:你得到:
bar
ban
bra
brn
bna
bnr
abr
abn
arb
arn
anb
anr
rba
rbn
rab
ran
rnb
rna
nba
nbr
nab
nar
nrb
nra
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.