Google笔试题_改进

有数量不限的面值为100,50,20,10,5,1元的纸币,问要组成N(N<=10^6)共有多少种组合方式?(Google笔试题)

首先用深搜思想实现的枚举
#include <cstdio>
#define COM_LEN 6
using namespace std;

int com[COM_LEN] = {1, 5, 10, 20, 50, 100};
void cal_combinations(int num, int *arr, int index, int &res) {
    if (0 == num) {
        ++res;
        return;
    }

    if (index < 0)
        return;

    int i, t;

    t = num / com[index];
    for (i = 0; i <= t; ++i) {
        cal_combinations(num - com[index] * i, arr, index - 1, res);
    }
}

int main() {
    int i, res;

    for (i = 1; i <= 200; ++i) {
        res = 0;
        cal_combinations(i, com, COM_LEN - 1, res);
        printf("%d->%d\n", i, res);
    }
    return 0;
}

二维动态规划的改进(受百度工程师http://weibo.com/changneng和民哥http://weibo.com/1241210631启发)

d[n][100] = d[n-100][100]+d[n-100][50]+d[n-100][20]+d[n-100][10]+d[n-100][5]+d[n-100][1];d[n][50] = d[n-50][50]+d[n-50][20]+d[n-50][10]+d[n-50][5]+d[n-50][1];

设d[n][k]表示面值为n、最大面额的纸币为k的组合数据量

d[n][20] = d[n-20][20]+d[n-20][10]+d[n-20][5]+d[n-20][1];
d[n][10] = d[n-10][10]+d[n-10][5]+d[n-10][1];
d[n][5] = d[n-5][5]+d[n-5][1];
d[n][1] = d[n-1][1];
d[1][1]=d[5][5]=d[10][10]=d[20][20]=d[50][50]=d[100][100]=1;
最后f(n)=d[n][100]+d[n][50]+d[n][20]+d[n][10]+d[n][5]+d[n][1];
posted @ 2011-10-15 10:43  杨雨_AlexYang  阅读(858)  评论(1编辑  收藏  举报