java - Count All Permutations Where No Two Adjacent Characters Are the Same -


given sequence contains various amounts of numbers 1, 2, 3, , 4 (examples: 13244, 4442, etc), want count permutations such no 2 adjacent numbers same. believe o(n! * n) , want know if there better 1 out there. have ideas?

 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 repeating adjacent characters                 for(int = 0; < prefix.length()-1; i++){                     if(prefix.charat(i)==prefix.charat(i+1))                         bad = true;                 }                 if(!bad){                     permutationcount++;                 }             }             else {                 //recurse through permutations                 (int = 0; < n; i++)                     permutation(prefix + str.charat(i), str.substring(0, i) + str.substring(i+1, n));             }         }     } 

i understand question this: given string containing numbers 1,2,3,4 - how many permutations of these characters exist when put them string again there won't same adjecent numbers.

i suggest approach:

  l - length of string   n1 - how many times 1 repeated, n2 - how many times 2 repeated etc.    p - number of possible permutations   p = l! / (n1!*n2!*n3!*n4!)    c - number of solutions fitting constraint   c = p - start permutations    substract permutations have 11 in (just take 11 1 number)   c = c - (l - 1)! / ((n1 - 1)! * n2! * n3! * n4!)    ... same 22 ...    add permutations have both 11 , 22 in (because have substracted them twice, need add them)   c = c + (l - 2)! / ((n1 - 1)! * (n2 - 1)! * n3! * n4!)    ... repeat previous steps 33 , 44 ... 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -