【问题标题】:How many distinct integers can be formed by rearranging the digits of an integer. [Permutation]通过重新排列整数的数字可以形成多少个不同的整数。 [排列]
【发布时间】:2017-05-07 11:18:36
【问题描述】:

数字不应以零开头。

例子:

给定 123,ans = 3! = 6 [123, 132, 213, 231, 312, 321]

给定 1122,ans = 4!/2! = 6 [1122、1212、1221、2211、2121、2112]

给定 100,ans = 1 [010, 001 不允许]

我被要求编写一个 java 代码来解决这个问题。 我未能形成处理零的通用算法。请帮助我提供解决方案和一些阅读材料。

【问题讨论】:

  • 不是1122 = 4的排列数吗! /(2!·2!)?那是一个2!在每组 2 位数字的分母中,其位置可互换。

标签: algorithm permutation


【解决方案1】:

编写一个查找组合数量的函数。假设它被称为 整数 com(列表编号);要实现这一点,请阅读:https://en.wikipedia.org/wiki/Combination

现在要解决这个问题,首先查找总数可以通过com(listOfNumbers)找到。然后找出开头为0的组合数,然后减去它。

例如:

1122

Total combinations possible com(1122) = 4! / (2! X 2!) 
Total numbers starting with 0 = 0

So ans = 4! / (2! X 2!)

001122

Total combinations possible com(001122) = 6! / (2! X 2! X 2!)
Total numbers starting with 0 
= fix one 0 in the beginning and find all possible combination for the rest of the numbers 
= com(01122) = 5! / (2! X 2!)

So ans = com(001122) - com(01122)

001

Total combinations possible com(001) = 3! / (2!) = 3
Total numbers starting with 0 
= fix one 0 in the beginning and find all possible combination for the rest of the numbers 
= com(01) = 2! = 2

So ans = com(001) - com(01) = 1

【讨论】:

    【解决方案2】:

    这样分组你的数字:

     0: m[0] times
     1: m[1] times
     2: m[2] times
     ...
     9: m[9] times
     overall number of digits: N
    

    那么排列数是N!,没有重复的排列数是

    PwR = N! / (m[0]! * m[1]!.. * m[9]!)
    

    注意有前导零的ZwR排列(考虑没有一个零的同一个集合(如果m[0] = 0,忽略这部分):

    ZwR = (N-1)! / ((m[0] - 1)! * m[1]!.. * m[9]!)
    

    所以有效结果的数量是

    P = PwR - ZwR = 
           N! / (m[0]! * m[1]!.. * m[9]!) - 
          (N-1)! / ((m[0] - 1)! * m[1]!.. * m[9]!) =  
      //separate common multiplier
         (N-1)! / ((m[0] - 1)! * m[1]!.. * m[9]!) * (N/m[0] - 1)
    

    对于您的 001 示例:

      N=3, m[0]=2, m[1] = 1
      P = (3-1)! / (1!*1!) * (3/2 - 1) = 2 * 1/2 = 1
    

    【讨论】:

      猜你喜欢
      • 2013-06-26
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      相关资源
      最近更新 更多