Created
April 25, 2018 05:41
-
-
Save marklin-latte/920323ef14e363b019397f1477efc9c9 to your computer and use it in GitHub Desktop.
Coin Change II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int result; | |
/** | |
* @param amount: a total amount of money amount | |
* @param coins: the denomination of each coin | |
* @return: the number of combinations that make up the amount | |
*/ | |
public int change(int amount, int[] coins) { | |
// write your code here | |
if(coins == null || coins.length == 0 ){ | |
return -1; | |
} | |
Arrays.sort(coins); | |
this.result = 0; | |
dfsHelper(amount, coins, new ArrayList<Integer>(),0); | |
return this.result; | |
} | |
// 計算每一種硬幣的組合,並且判斷如果該組合已大於 amount 則不繼續 dfs。 | |
// ex. [2] => [2,2],[2,3],[2,8] | |
// [3] => [3,2],[3,3],[3,8] | |
public void dfsHelper(int amount, | |
int[] coins, | |
ArrayList subCoins, | |
int startIndex | |
){ | |
if(amount < 0){ | |
return; | |
} | |
if(amount == 0){ | |
this.result++; | |
return; | |
} | |
for(int i=startIndex; i < coins.length; i++){ | |
if(i > 0 && coins[i] == coins[i-1]){ | |
continue; | |
} | |
subCoins.add(coins[i]); | |
amount -= coins[i]; | |
dfsHelper(amount, coins, subCoins, i); | |
amount += coins[i]; | |
subCoins.remove(subCoins.size() - 1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment