【问题标题】:recursive solution for coin change problem硬币找零问题的递归解法
【发布时间】:2020-04-11 06:08:28
【问题描述】:

我需要编写一个算法,它接收一个数字和一个数字列表,并从列表中返回可以创建总和数的数字的可能组合的数量。例如: def coin(5,[1,2,5,6] 应该返回数字 4,因为列表中有 4 种可能的组合可以一起创建数字 5。下面是我尝试过的代码,但确实如此不工作。输出是 6 而不是 4,我希望能帮助我理解原因。

def coin(n,lst):
    if n<=1:
        return 1
    else:
        total=0
        for i in range(len(lst)):
            change=lst[i]
            if change>n:
                continue
            else:
                result=coin(n-change,lst[i:])
                if result>0:
                    total+=result
        return total
print(coin(5,[1,2,5,6]))

【问题讨论】:

    标签: python-3.x recursion coin-change


    【解决方案1】:

    错误在于基本情况:

        if n<=1:
            return 1
    

    这仅在1 是允许的硬币之一时有效。但是在您的递归情况下,您将列表分割为lst[i:],因此并非每次都允许所有硬币。有时,1 不是允许的硬币之一,在这种情况下,总共有 1 种方法,而不是一种方法。要修复它,请编写如下内容:

        if n <= 1:
            if n == 0 or n in lst:
                return 1
            else:
                return 0
    

    这是正确的,因为您可以在基本情况下为n 进行更改,如果n 为0(我们总是可以为0),或者n 为1 并且1 是允许的硬币之一。

    也就是说,让递归case处理1会更简单,所以base case只需要处理0;这也是正确的:

        if n == 0:
            return 1
    

    【讨论】:

      【解决方案2】:
      int coinCount( int C[], int m, int n )
      
          {
              // if n is 0 return 1
              if (n == 0)
              return 1;
      
              // If n is less than 0 then no solution exists
              if (n < 0)
              return 0;
      
              // If there are no coins and n is greater than 0, then no solution exists
              if (m <=0 && n > 0)
              return 0;
      
              return coinCount( C, m - 1, n ) + coinCount( C, m, n-C[m-1] );
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-02
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 1970-01-01
        • 2015-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多