我必须创建一个递归函数,它告诉您一个数字的0.分可以变成变化的方式的数量。(使用硬币、一角硬币和便士)。
到目前为止,我有一个递归函数来完成这个任务,但是它不止一次计算相同的组合,所以这个数字太大了。如何删除重复的组合?
代码:
#include <stdio.h>
//Prototypes
int coins(int);
int main(void){
//Declarations
int num;
//Get user input
printf("Enter an amount of change in cents: ");
scanf("%d", &num); //Change to fgets
//Call function
printf("There are %d ways to make change for %d cents.\n", (coins(num)), num);
}
int coins(int amt){
//Declarations
int ways=0;
//Base Case
if(amt == 0){
return 1;
}
//int ways=0; More efficient after base case.
if(amt >= 1){
ways+=coins(amt-1);
}
if(amt >= 5){
ways+=coins(amt-5);
}
if(amt >= 10){
ways+=coins(amt-10);
}
if(amt >= 25){
ways+=coins(amt-25);
}
return ways;
}示例:
投入: 17 (美分)
产出: 80种方式**产出应为6
发布于 2015-11-11 02:02:46
#include <stdio.h>
int coins(int, int);
int main(void){
int num;
printf("Enter an amount of change in cents: ");
scanf("%d", &num);
printf("There are %d ways to make change for %d cents.\n", coins(num, 0), num);
return 0;
}
int coins(int amt, int kind){
static int kinds[4] = {25, 10, 5, 1};
int ways=0, i, n;
if(kinds[kind] == 1)//always divisible
return 1;
n = amt / kinds[kind];
for(i = 0; i <= n; ++i)
ways+=coins(amt-kinds[kind]*i, kind + 1);
return ways;
}https://stackoverflow.com/questions/33642780
复制相似问题