首頁  >  文章  >  後端開發  >  C程式找零錢

C程式找零錢

PHPz
PHPz轉載
2023-08-29 08:37:06878瀏覽

C程式找零錢

在這個問題中,我們給定一個值n,我們想要找零n盧比,並且我們有n個硬幣,每個硬幣的面值從1到m不等。我們需要傳回能夠組成這個總和的方式的總數。

範例

Input : N = 6 ; coins = {1,2,4}.
Output : 6
Explanation : The total combination that make the sum of 6
is :
{1,1,1,1,1,1} ; {1,1,1,1,2}; {1,1,2,2}; {1,1,4}; {2,2,2} ; {2,4}.

Example

的中文翻譯為:

範例

#include <stdio.h>
int coins( int S[], int m, int n ) {
   int i, j, x, y;
   int table[n+1][m];
   for (i=0; i<m; i++)
      table[0][i] = 1;
   for (i = 1; i < n+1; i++) {
      for (j = 0; j < m; j++) {
         x = (i-S[j] >= 0)? table[i - S[j]][j]: 0;
         y = (j >= 1)? table[i][j-1]: 0;
         table[i][j] = x + y;
      }
   }
   return table[n][m-1];
}
int main() {
   int arr[] = {1, 2, 3};
   int m = sizeof(arr)/sizeof(arr[0]);
   int n = 4;
   printf("The total number of combinations of coins that sum up to %d",n);
   printf(" is %d ", coins(arr, m, n));
   return 0;
}

輸出

The total number of combinations of coins that sum up to 4 is 4

以上是C程式找零錢的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除