绠楁硶鍔ㄦ€佽鍒掞紙涓冿級-鑳屽寘闂4
Posted Coding鐨勫摂鍝斿彣鍙?/a>
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了绠楁硶鍔ㄦ€佽鍒掞紙涓冿級-鑳屽寘闂4相关的知识,希望对你有一定的参考价值。
杈撳叆锛?span class="code-snippet__selector-attr">[1,2,5] , 11
杈撳嚭锛?銆?+5+5=11
杈撳叆锛?span class="code-snippet__selector-attr">[2],3
杈撳嚭锛?span class="code-snippet__selector-tag">-1锛?/span>
馃檵瑙f硶涓€锛?span>璁板繂鍖栭€掑綊
馃檱鎬濊矾锛?/span>
Map<Integer,Integer> map = new HashMap<>();
public int coinChange(int[] coins, int amount) {
if(amount <= 0){
return 0;
}
return find_h(coins,amount);
}
private int find_h(int[] nums,int amount){
if(amount <0){
return -1;
}
if(amount == 0){
return 0;
}
if(map.containsKey(amount)){
return map.get(amount);
}
int count=Integer.MAX_VALUE;
for(int num:nums){
if(num > amount){
continue;
}
int solu=find_h(nums,amount-num);
if(solu>=0){
count = Math.min(count,solu+1);
}
}
if(count == Integer.MAX_VALUE){
count =-1;
}
map.put(amount,count);
return map.get(amount);
}
馃檵瑙f硶浜岋細鍔ㄦ€佽鍒掋€愯嚜涓婅€屼笅銆?/span>
馃檱鎬濊矾锛?/span>
鐘舵€佸畾涔?/span>锛?/span>F(S)锛屽噾榻愭€婚噾棰漇锛岄渶瑕佺殑鏈€灏忕‖甯佹暟銆?/p>
鐘舵€佽浆绉绘柟绋?/span>锛?/span>F(S) = F(S-coins[i]) + 1銆?/span> 馃檵瑙f硶涓夛細鍔ㄦ€佽鍒掋€愯嚜涓嬭€屼笂銆?/strong> 馃檱鎬濊矾锛?/span> 鐘舵€佸畾涔?/span>锛歞p[j]锛屽噾榻愭€婚噾棰漥锛岄渶瑕佺殑鏈€灏忕‖甯佹暟銆?/p>
鐘舵€佽浆绉绘柟绋?/span>锛歞p[i][j]= min(dp[i][j],dp[i](j-coins[i]) + 1)銆傚噾榻愭€婚噾棰漥闇€瑕佺殑鏈€灏忕‖甯佹暟锛屽綋鍦癷涓‖甯侀€夋垨鑰呬笉閫変袱绉嶆儏鍐点€?/span>
澶嶆潅搴﹀垎鏋?/span> 鏃堕棿澶嶆潅搴︼細O(SN)锛氳繖閲孲鏄€婚噾棰濓紝N鏄彁渚涚殑涓嶅悓闈㈤鏁帮紝鍗虫暟缁勯暱搴︺€傛垜浠璁$畻O(S)涓笉鍚屾€婚噾棰濓紝瀵规瘡娆$殑鎬婚噾棰濋渶瑕丯涓潰棰濇潵杞Щ鐘舵€侊紝涓€鍏遍渶瑕丱(SN)鐨勬椂闂村鏉傚害銆?/span> 绌洪棿澶嶆潅搴︼細O(S)锛屾垜浠娇鐢ㄤ簡涓€涓猄+1鐨刣p鏁扮粍銆?/span> 涓嶇Н璺锛屾棤浠ヨ嚦鍗冮噷銆?/strong> 鏂囩珷鏈夊府鍔╃殑璇濓紝鐐逛釜杞彂銆佸湪鐪嬪憲銆?/strong> 璋㈣阿鏀寔鍝?(*^__^*) END 馃憞 以上是关于绠楁硶鍔ㄦ€佽鍒掞紙涓冿級-鑳屽寘闂4的主要内容,如果未能解决你的问题,请参考以下文章
public int coinChange(int[] coins, int amount) {
if (amount < 1) return 0;
return coinChange_h(coins, amount,new int[amount+1]);
}
private int coinChange_h(int[] coins, int amount,int[] count) {
if (amount < 0) return -1;
if (amount == 0) return 0;
if (count[amount] != 0) return count[amount];
int min = Integer.MAX_VALUE;
for (int coin : coins) {
int res = coinChange_h(coins, amount - coin,count);
if (res >= 0 )
min = Math.min(1 + res,min);
}
count[amount] = min == Integer.MAX_VALUE ? -1:min;
return count[amount];
}
public int coinChange_2(int[] coins, int amount) {
if (amount < 1) return 0;
int[] dp = new int[amount+1];
Arrays.fill(dp,amount+1);
//杩欏効瑙i噴涓嬩负鍟ラ粯璁ゅ~鍏卆mount+1锛屽噾榻恆mount鏈€澶氫篃灏辨槸闈㈠€间负1鐨勬暟鎬昏鐢╝mount涓紝
// 鎵€浠ユ渶灏戜釜鏁颁竴瀹氭槸<amount+1鐨?/span>
dp[0]=0;
for(int j=1;j<=amount;j++){
for(int num:coins){
if(num <= j){
dp[j]=Math.min(dp[j],dp[j-num]+1);
}
}
}
return dp[amount]==amount+1?-1:dp[amount];
}