首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除递归函数中的重复结果

删除递归函数中的重复结果
EN

Stack Overflow用户
提问于 2015-11-11 01:27:02
回答 1查看 389关注 0票数 2

我必须创建一个递归函数,它告诉您一个数字的0.分可以变成变化的方式的数量。(使用硬币、一角硬币和便士)。

到目前为止,我有一个递归函数来完成这个任务,但是它不止一次计算相同的组合,所以这个数字太大了。如何删除重复的组合?

代码:

代码语言:javascript
复制
 #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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-11 02:02:46

代码语言:javascript
复制
#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;
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33642780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档