Q9.8 Combine Sum

Q:Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and pennies (1 cent), write code to calculate the number of ways of representing n cents.

A:

思路:DFS

例如要构造100,则:

取0个1分的,再递归调用凑够100; 取1个1分的,再递归调用凑够99; 取2个1分的,再递归调用凑够98;...;取100个1分的,再递归调用凑合0,

取了若干个1分的之后,再同样的递归方法取用若干个5分的,若干个10分的,若干个25分的。最终得到结果。

#include 
#include 
using namespace std;

int res = 0;

void conmbineSum(vector &candidate, int gap, int start) {
	if (gap < 0 || start == candidate.size()) {
		return ;
	}
	if (gap == 0) {
		res++;
		return ;
	}
	for (int i = start; i < candidate.size(); i++) {
		if (gap < candidate[i]) return ;
		conmbineSum(candidate, gap-candidate[i], i);
	}
}

int conmbineSum2(int n, int denom){
    int next_denom = 0;
    switch(denom){
    case 25:
        next_denom = 10;
        break;
    case 10:
        next_denom = 5;
        break;
    case 5:
        next_denom = 1;
        break;
    case 1:
        return 1;
    }
    int ways = 0;
    for(int i=0; i*denom<=n; ++i)
        ways += conmbineSum2(n-i*denom, next_denom);
    return ways;
}

int main() {
	vector candidate(4,0);
	candidate[0] = 1;
	candidate[1] = 5;
	candidate[2] = 10;
	candidate[3] = 25;
	conmbineSum(candidate, 100, 0);
	cout<



你可能感兴趣的:(Cracking,the,coding,interview)