gpt4 book ai didi

java - Coin change DP解决方案来跟踪硬币

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:17:49 26 4
gpt4 key购买 nike

尝试为一般硬币找零问题编写 DP 解决方案,同时跟踪使用了哪些硬币。到目前为止,我一直在努力为我提供所需的最少硬币数量,但无法弄清楚如何获得使用了哪些硬币以及使用了多少次。如果使用硬币,我尝试用值设置另一个表( boolean 值),但这似乎无法正常工作。有什么想法吗?

public static int minChange(int[] denom, int changeAmount) 
{
int m = denom.length;
int n = changeAmount + 1;

int[][] table = new int[m][n];
boolean[][] used = new boolean[m][n];
for (int j = 0; j < n; j++)
table[m - 1][j] = j;
for (int i = 0; i < m; i++)
table[i][0] = 0;

for (int i = m-2; i >= 0; i--) //i denotes denominationIndex
{
for (int j = 1; j < n; j++) //j denotes current Amount
{
if (denom[i] > j)
{
table[i][j] = table[i+1][j];
//used[i][j] = false;
}
else
{
table[i][j] = Math.min(1 + table[i][j-denom[i]], table[i+1][j]);
/*Trying table for used coins
if (1 + table[i][j-denom[i]] < table[i+1][j])
used[i][j] = true;
else
used[i][j] = false;
*/
}
}
}
}

最佳答案

试试这个解决方案,它只使用 O(M) 内存并且具有 O(N*M) 复杂度:

   public static int[] minChange(int[] denom, int changeAmount)
{
int n = denom.length;
int[] count = new int[changeAmount + 1];
int[] from = new int[changeAmount + 1];

count[0] = 1;
for (int i = 0 ; i < changeAmount; i++)
if (count[i] > 0)
for (int j = 0; j < n; j++)
{
int p = i + denom[j];
if (p <= changeAmount)
{
if (count[p] == 0 || count[p] > count[i] + 1)
{
count[p] = count[i] + 1;
from[p] = j;
}
}
}

// No solutions:
if (count[changeAmount] == 0)
return null;

// Build answer.
int[] result = new int[count[changeAmount] - 1];
int k = changeAmount;
while (k > 0)
{
result[count[k] - 2] = denom[from[k]];
k = k - denom[from[k]];
}

return result;
}

关于java - Coin change DP解决方案来跟踪硬币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20185590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com