java – 计算没有两个相邻字符相同的所有排列

给定一个只包含不同数量的数字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));
            }
        }
    }
最佳答案
我理解你的问题是这样的:给定一个只包含数字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 ...

转载注明原文:java – 计算没有两个相邻字符相同的所有排列 - 代码日志