给定一个只包含不同数量的数字1,2,3和4的序列(例如:13244,4442等),我想计算它的所有排列,使得没有两个相邻的数字是相同的。我相信它是O(N!* N)并想知道那里是否有更好的一个。有人有什么想法吗?
class Ideone
{
static int permutationCount++;
public static void main(String[] args) {
String str = "442213";
permutation("", str);
System.out.println(permutationCount);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0){
boolean bad = false;
//Check whether there are repeating adjacent characters
for(int i = 0; i < prefix.length()-1; i++){
if(prefix.charAt(i)==prefix.charAt(i+1))
bad = true;
}
if(!bad){
permutationCount++;
}
}
else {
//Recurse through permutations
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
}
答案 0 :(得分:1)
我理解你的问题是这样的:给定一个只包含数字1,2,3,4的字符串 - 这些字符存在多少个排列,当你再次将它们放入字符串时,就不会有任何相同的元素号。
我会建议这种方法:
L - length of your string
n1 - how many times is 1 repeated, n2 - how many times is 2 repeated etc.
P - number of all possible permutations
P = L! / (n1!*n2!*n3!*n4!)
C - number of all solutions fitting your constraint
C = P - start with all permutations
substract all permutations which have 11 in it (just take 11 as one number)
C = C - (L - 1)! / ((n1 - 1)! * n2! * n3! * n4!)
... do the same for 22 ...
add all permutations which have both 11 and 22 in it (because we have substracted them twice, so you need to add them)
C = C + (L - 2)! / ((n1 - 1)! * (n2 - 1)! * n3! * n4!)
... repeat previous steps for 33 and 44 ...
答案 1 :(得分:0)
如果您只想计算多少排列符合您的约束,则不需要拼写每个排列。
如果我的问题正确,您的输入字符串有4个不同的输入字符1,2,3,4
,您想知道这可能有多少种排列?
然后你应该使用一些数学,即n! / (n-r)!
,其中n
是可供选择的元素数量(本例中为4),r
是你想要的位置数量填补(也是4)。
您的示例可能会有4! / (4-4)! = 24
个排列:
{1,2,3,4} {1,2,4,3} {1,3,2,4} {1,3,4,2} {1,4,2,3} {1,4,3,2}
{2,1,3,4} {2,1,4,3} {2,3,1,4} {2,3,4,1} {2,4,1,3} {2,4,3,1}
{3,1,2,4} {3,1,4,2} {3,2,1,4} {3,2,4,1} {3,4,1,2} {3,4,2,1}
{4,1,2,3} {4,1,3,2} {4,2,1,3} {4,2,3,1} {4,3,1,2} {4,3,2,1}
简而言之,对于n
长度n
个不同的值,排列数为n!
:
1 -> 1
2 -> 2
3 -> 6
4 -> 24
5 -> 120
...
答案 2 :(得分:0)
编辑:在您的编辑和评论之后,很明显我误解了这个问题。
如果您只是想检查相邻的数字是否匹配,那么您可以使用简单的循环。这将是O(n)复杂性。
public static void main(String[] args) {
String str = "442213";
System.out.println(permutation(str));
}
public static int permutation(String str) {
int permutationCount = 0;
if (str.length() > 1) {
for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) != str.charAt(i + 1)) {
permutationCount++;
}
}
}
return permutationCount;
}
如果你想坚持递归,你可以这样做:
public static void main(String[] args) {
String str = "442213";
System.out.println(permutation(str, 0));
}
public static int permutation(String str, int currentIndex) {
int permutationCount = 0;
if (str == null || currentIndex + 1 >= str.length()) {
return permutationCount;
}
if (str.charAt(currentIndex) != str.charAt(currentIndex + 1)) {
permutationCount = 1;
}
return permutationCount + permutation(str, currentIndex + 1);
}