Coin Change |
Suppose there are 5 types of coins: 50-cent, 25-cent, 10-cent, 5-cent, and 1-cent. We want to make changes with these coins for a given amount of money.
For example, if we have 11 cents, then we can make changes with one 10-cent coin and one 1-cent coin, two 5-cent coins and one 1-cent coin, one 5-cent coin and six 1-cent coins, or eleven 1-cent coins. So there are four ways of making changes for 11 cents with the above coins. Note that we count that there is one way of making change for zero cent.
Write a program to find the total number of different ways of making changes for any amount of money in cents. Your program should be able to handle up to 7489 cents.
11 26
4 13
棰樼洰澶ф剰錛?/p>
緇欏畾1 5 10 25 50浜旂紜竵錛岀粰瀹氫竴涓暟錛岄棶鐢ㄨ繖浜涚‖甯佹湁澶氬皯縐嶄笉鍚岀殑緇勫悎鏂瑰紡錛?/p>
鎯蟲兂濂藉儚鍙互鏄竴涓柟紼嬬粍姹傝В鐨勯棶棰樺槢錛?/p>
x1+5*x2+10*x3+25*x4+50*x5=x0;
緇欏畾x0錛屼竴緇勬弧瓚蟲潯浠剁殑x>=0灝辨槸瑙i泦銆傚晩鍝堝搱鍝堛傚彲浠ラ珮鏂秷鍏冩硶鍜?/p>
涓嶈繃錛屾槑鏄劇殑璁℃暟闂錛?/p>
dp[i][j]琛ㄧずi鍙互鐢卞墠j縐嶇‖甯佽〃紺虹殑鏂規(guī)硶鏁般?/p>
dp[i][j]=dp[i][j-1]+dp[i-coin[j]][j] i-coin[j]>0
dp[i][j]=dp[i][j-1]+1 i-coin[j]=0;
dp[i][j]=dp[i][j-1] i-coin[j]<0
鏂圭▼綾婚棶棰橈紝涓瀹氳鍏堟妸鏂圭▼鍐欐竻妤氾紒錛侊紒
Coin Change |
Suppose there are 5 types of coins: 50-cent, 25-cent, 10-cent, 5-cent, and 1-cent. We want to make changes with these coins for a given amount of money.
For example, if we have 11 cents, then we can make changes with one 10-cent coin and one 1-cent coin, two 5-cent coins and one 1-cent coin, one 5-cent coin and six 1-cent coins, or eleven 1-cent coins. So there are four ways of making changes for 11 cents with the above coins. Note that we count that there is one way of making change for zero cent.
Write a program to find the total number of different ways of making changes for any amount of money in cents. Your program should be able to handle up to 7489 cents.
11 26
4 13
棰樼洰澶ф剰錛?/p>
緇欏畾1 5 10 25 50浜旂紜竵錛岀粰瀹氫竴涓暟錛岄棶鐢ㄨ繖浜涚‖甯佹湁澶氬皯縐嶄笉鍚岀殑緇勫悎鏂瑰紡錛?/p>
鎯蟲兂濂藉儚鍙互鏄竴涓柟紼嬬粍姹傝В鐨勯棶棰樺槢錛?/p>
x1+5*x2+10*x3+25*x4+50*x5=x0;
緇欏畾x0錛屼竴緇勬弧瓚蟲潯浠剁殑x>=0灝辨槸瑙i泦銆傚晩鍝堝搱鍝堛傚彲浠ラ珮鏂秷鍏冩硶鍜?/p>
涓嶈繃錛屾槑鏄劇殑璁℃暟闂錛?/p>
dp[i][j]琛ㄧずi鍙互鐢卞墠j縐嶇‖甯佽〃紺虹殑鏂規(guī)硶鏁般?/p>
dp[i][j]=dp[i][j-1]+dp[i-coin[j]][j] i-coin[j]>0
dp[i][j]=dp[i][j-1]+1 i-coin[j]=0;
dp[i][j]=dp[i][j-1] i-coin[j]<0
鏂圭▼綾婚棶棰橈紝涓瀹氳鍏堟妸鏂圭▼鍐欐竻妤氾紒錛侊紒