遍歷N叉樹
public void inOrder(Node root) {
if(root == null) {
return;
}
res.add(root.val);
int s = root.children.size();
for(int i = 0; i < s; i++) {
inOrder(root.children.get(i));
}
}
暴力解法
int res = Integer.MAX_VALUE;
public int coinChange(int[] coins, int amount) {
if(coins.length == 0){
return -1;
}
findWay(coins,amount,0);
// 如果沒有任何一種硬幣組合能組成總金額,回傳 -1,
if(res == Integer.MAX_VALUE){
return -1;
}
return res;
}
public void findWay(int[] coins,int amount,int count){
if(amount < 0){
return;
}
if(amount == 0){
res = Math.min(res,count);
}
for(int i = 0;i < coins.length;i++){
// amount-coins[i]作為root.children.get(i)
findWay(coins,amount-coins[i],count+1);
}
}
優化
int res = Integer.MAX_VALUE;
//+++++++++
int[] memo;
public int coinChange(int[] coins, int amount) {
if(coins.length == 0){
return -1;
}
//++++++++
memo = new int[amount];
return findWay(coins,amount);
}
// memo[n] 表示錢幣n可以被換取的最少的硬幣數,不能換取就為-1
// findWay函式的目的是為了找到 amount數量的零錢可以兌換的最少硬幣數量,回傳其值int
public int findWay(int[] coins,int amount){
if(amount < 0){
return -1;
}
if(amount == 0){
return 0;
}
// 記憶化的處理,memo[n]用賦予了值,就不用繼續下面的回圈
// 直接的回傳memo[n] 的最優值
//+++++++++++++++
if(memo[amount-1] != 0){
return memo[amount-1];
}
int min = Integer.MAX_VALUE;
for(int i = 0;i < coins.length;i++){
int res = findWay(coins,amount-coins[i]);
//++++++++++++++++
if(res >= 0 && res < min){
min = res + 1; // 加1,是為了加上得到res結果的那個步驟中,兌換的一個硬幣
}
}
//+++++++++++++++++
memo[amount-1] = (min == Integer.MAX_VALUE ? -1 : min);
return memo[amount-1];
}
使用迭代
public int coinChange(int[] coins, int amount) {
// 自底向上的動態規劃
if(coins.length == 0){
return -1;
}
// memo[n]的值: 表示的湊成總金額為n所需的最少的硬幣個數
int[] memo = new int[amount+1];
memo[0] = 0;
for(int i = 1; i <= amount;i++){
int min = Integer.MAX_VALUE;
for(int j = 0;j < coins.length;j++){
if(i - coins[j] >= 0 && memo[i-coins[j]] < min){
min = memo[i-coins[j]] + 1;
}
}
// memo[i] = (min == Integer.MAX_VALUE ? Integer.MAX_VALUE : min);
memo[i] = min;
}
return memo[amount] == Integer.MAX_VALUE ? -1 : memo[amount];
}
memo[i] 有兩種實作的方式,去兩者的最小值
-
包含當前的
coins[i],那么剩余錢就是i?coins[i],這種操作要兌換的硬幣數是memo[i?coins[j]]+1 -
不包含,要兌換的硬幣數是
memo[i]
public int coinChange(int[] coins, int amount) {
// 自底向上的動態規劃
if(coins.length == 0){
return -1;
}
// memo[n]的值: 表示的湊成總金額為n所需的最少的硬幣個數
int[] memo = new int[amount+1];
// 給memo賦初值,最多的硬幣數就是全部使用面值1的硬幣進行換
// amount + 1 是不可能達到的換取數量,于是使用其進行填充
Arrays.fill(memo,amount+1);
memo[0] = 0;
for(int i = 1; i <= amount;i++){
for(int j = 0;j < coins.length;j++){
if(i - coins[j] >= 0){
// memo[i]有兩種實作的方式,
// 一種是包含當前的coins[i],那么剩余錢就是 i-coins[i],這種操作要兌換的硬幣數是 memo[i-coins[j]] + 1
// 另一種就是不包含,要兌換的硬幣數是memo[i]
memo[i] = Math.min(memo[i],memo[i-coins[j]] + 1);
}
}
}
return memo[amount] == (amount+1) ? -1 : memo[amount];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/244175.html
標籤:其他
上一篇:練習筆記-思科交換機2960新設備啟用等配置20201230
下一篇:軟體測驗基礎知識
