Change of Change:
There are an unlimited number of coins, the value of which is 25, 10, 5 and 1, please write code to calculate n there are several representations.
Given an int n, there are several representations of how to return N. Ensure that n is less than or equal to 100000, in order to prevent overflow, please add the answer mod 1000000007.
Test examples
6
Returns: 2
Dynamic planning
Dp[i][sum] How many ways to make sum with I coins.
Set the face value of a v1,v2,v3,v4 coin
sum = v1*x1+ v2*x2 + v3*x3 + v4*k; Dp[i][sum]
{X1,x2,x3,k}
{0...X1}
{0...X2}
{0...X3}
{0...K}
k<=sum/v4;
Sum_0 = v1*x1+ v2*x2 + v3*x3 + v4* (k); Dp[i-1][sum-v4*k]
Sum_1 = v1*x1+ v2*x2 + v3*x3 + v4* (k-1); dp[i-1][sum-v4* (k-1)]
Sum_2 = v1*x1+ v2*x2 + v3*x3 + v4* (k-2); dp[i-1][sum-v4* (k-2)]
.
.
.
.
.
Sum_n = v1*x1+ v2*x2 + v3*x3 + v4* (k-n); dp[i-1][sum-v4* (K-n)]
.
.
.
Sum_k = v1*x1+ v2*x2 + v3*x3 +v4* (k-k); Dp[i-1][sum]
sum = Sum_0+sum_1+sum_2+sum_3+......+sum_n+sum_k;
Dp[i][sum]=dp[i-1][sum] + dp[i-1][sum-v4]+....dp[i-1][sum-v4*n] +dp[i-1][sum-v4*k]; k<=sum/v4;
Dp[i][sum] can be derived from the previous line
Code:
Two-dimensional arrays:
public int countways (int n) {
int coin[] = new int[]{1,5,10,25};
int dp[][] = new int[5][n+1];
for (int i = 0; I <= 4; ++i)
{
Dp[i][0] = 1;
}
for (int i=1;i<=4;++i) {
for (int j=1;j<=n;++j) {
for (int k=0;k<=j/coin[i-1];++k) {
Dp[i][j]+=dp[i-1][j-k*coin[i-1]];
}
}
}
return dp[4][n];
}
Optimized for one-dimensional arrays:
Dp[i][sum]=dp[i-1][sum] + dp[i-1][sum-v4]+....dp[i-1][sum-v4*n] +dp[i-1][sum-v4*k]; k<=sum/v4;
Line: We just need the data from the previous row
Column: We only need the data before the current sum
One-dimensional arrays can be solved at a time by line
Suppose n=20
1 5 10 20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5
3 1 1 1 1 1 2 2 2 2 2 4 4 4 4 4 4 4 4 4 4 9
4 1 1 1 1 1 2 2 2 2 2 4 4 4 4 4 4 4 4 4 4 9
public int countways (int n) {
int[] coin = new int[]{1,5,10,25};
Int[] dp = new INT[N+1];
Dp[0]=1;
for (int i = 0; i < coin.length; i++) {
for (int j = coin[i]; j <= N; j + +) {
DP[J] = (Dp[j]+dp[j-coin[i]])%1000000007;
}
}
return dp[n];
}
Reference: http://www.cnblogs.com/python27/archive/2013/09/05/3303721.html title Source: http://www.nowcoder.com/practice/ c0503ca0a12d4256af33fce2712d7b24?tpid=8&tqid=11041&rp=3&ru=/ta/cracking-the-coding-interview& Qru=/ta/cracking-the-coding-interview/question-ranking