📜  C程序代币兑换

📅  最后修改于: 2021-05-28 05:06:35             🧑  作者: Mango

给定一个值N,如果我们要N分钱找零,并且我们有无限数量的S = {S1,S2,..,Sm}硬币的供应,我们可以用几种方法进行找零?硬币的顺序无关紧要。

例如,对于N = 4和S = {1,2,3},有四个解:{1,1,1,1},{1,1,2},{2,2},{1, 3}。因此输出应为4。对于N = 10且S = {2,5,3,6},有五个解:{2,2,2,2,2},{2,2,3,3}, {2,2,6},{2,3,5}和{5,5}。因此输出应为5。

C
// C program for coin change problem.
#include
  
int count( int S[], int m, int n )
{
    int i, j, x, y;
  
    // We need n+1 rows as the table is constructed 
    // in bottom up manner using the base case 0
    // value case (n = 0)
    int table[n+1][m];
     
    // Fill the enteries for 0 value case (n = 0)
    for (i=0; i= 0)? table[i - S[j]][j]: 0;
  
            // Count of solutions excluding S[j]
            y = (j >= 1)? table[i][j-1]: 0;
  
            // total count
            table[i][j] = x + y;
        }
    }
    return table[n][m-1];
}
  
// Driver program to test above function
int main()
{
    int arr[] = {1, 2, 3};
    int m = sizeof(arr)/sizeof(arr[0]);
    int n = 4;
    printf(" %d ", count(arr, m, n));
    return 0;
}


C
int count( int S[], int m, int n )
{
    // table[i] will be storing the number of solutions for
    // value i. We need n+1 rows as the table is constructed
    // in bottom up manner using the base case (n = 0)
    int table[n+1];
  
    // Initialize all table values as 0
    memset(table, 0, sizeof(table));
  
    // Base case (If given value is 0)
    table[0] = 1;
  
    // Pick all coins one by one and update the table[] values
    // after the index greater than or equal to the value of the
    // picked coin
    for(int i=0; i


输出:

4

时间复杂度:O(mn)

以下是方法2的简化版本。此处所需的辅助空间仅为O(n)。

C

int count( int S[], int m, int n )
{
    // table[i] will be storing the number of solutions for
    // value i. We need n+1 rows as the table is constructed
    // in bottom up manner using the base case (n = 0)
    int table[n+1];
  
    // Initialize all table values as 0
    memset(table, 0, sizeof(table));
  
    // Base case (If given value is 0)
    table[0] = 1;
  
    // Pick all coins one by one and update the table[] values
    // after the index greater than or equal to the value of the
    // picked coin
    for(int i=0; i

请参考有关动态编程的完整文章。设置7(硬币找零)了解更多详细信息!

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。