投硬币问题

xiaoxiao2021-02-28  119

想兑换100元零钱,有1元,2元,5元,10元四种面值,总共有多少种兑换方法 目前只想到穷举法:

点击(此处)折叠或打开

#include<stdio.h> #include<stdlib.h> int kindofMoney( ) {     int l1,l2,l5,l10;     int count = 0;     for (l1 = 0;l1 <= 100;l1++)     {         for (l2 = 0;l2<=50;l2++)         {             for (l5 = 0;l5<=20;l5++)             {                 for (l10 = 0;l10 <= 10;l10++)                 if (l1*1+l2*2+l5*5+l10*10 == 100)                 count++;             }         }         }     return count; } int main() {     int result = kindofMoney();     printf("%d\n",result);     return 0; } 运行结果(centos5.5) [root@localhost ~]# ./a.out 2156 [root@localhost ~]#  有种错误的方法代码如下:

点击(此处)折叠或打开

#include<iostream> using namespace std; //int count = 0; long long kindOfMoney(unsigned int n){     if (n == 0) return 0;     if (n == 1) return 1;     if (n == 2) return 2;     if (n == 3) return 2;     if (n == 4) return 3;     if (n == 5) return 4;     if (n == 6) return 5;     if (n == 7) return 6;     if (n == 8) return 7;     if (n == 9) return 8;     if (n == 10) return 11;     return kindOfMoney(n-1)+kindOfMoney(n-2)+kindOfMoney(n-5)+kindOfMoney(n-10); } int main(){     long long result = kindOfMoney(11);     cout << result << endl;     //system("pause");     return 0; } 错误在1+10和10+1是不同的两种,考虑了顺序 可有更好的办法? <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script> 阅读(334) | 评论(0) | 转发(0) | 0

上一篇:跳台阶问题

下一篇:荷兰国旗问题

相关热门文章 test123编写安全代码——小心有符号数...使用openssl api进行加密解密...一段自己打印自己的c程序...彻底搞定C语言指针详解-完整版... 给主人留下些什么吧!~~ 评论热议
转载请注明原文地址: https://www.6miu.com/read-56646.html

最新回复(0)