Coin change

来源:互联网 发布:看本子的软件 编辑:程序博客网 时间:2024/05/22 10:35

http://www.fgdsb.com/2015/01/03/coin-change-problem/#more

Given a set of currency denominations, find the minimum number of coins needed to represent an amount.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int minCoins(int a[], int n, int t){
    vector<int> dp(t+1,0);
    int minVal;
    for(int i = 1; i <= t; i++){
        minVal = i;
        for (int j = 0; j < n; j++)
            if(a[j] <= i)
                minVal = min(dp[i-a[j]]+1,minVal);
            else
                break;
        dp[i] = minVal;
    }
    return dp[t];
}

Follow Up:
How many ways can we make the change?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int count( int S[], int m, int n ) {
    // table[i] will be storing the number of solutions for
    // value i. We need n+1 rows as the table is consturcted
    // in bottom up manner using the base case (n = 0)
    vector<int> table(n+1, 0);
   
    // Base case (If given value is 0)
    table[0] = 1;
   
    // Pick all coins one by one and update the table[] values
    // after the index greater than or equal to the value of the
    // picked coin
    for(int i=0; i<m; i++)
        for(int j=S[i]; j<=n; j++)
            table[j] += table[j-S[i]];
   
    return table[n];
}

0 0