Skip to content

Instantly share code, notes, and snippets.

@rayjcwu
Created March 21, 2014 04:44
Show Gist options
  • Select an option

  • Save rayjcwu/9679665 to your computer and use it in GitHub Desktop.

Select an option

Save rayjcwu/9679665 to your computer and use it in GitHub Desktop.
// wrong
public int ways(int x) {
int[] ans = new int[x + 1];
for (int i = 1; i < ans.length; i++) {
if (i == 1 || i == 5 || i == 10) {
ans[i] += 1;
}
if (i - 1 > 0) {
ans[i] += ans[i - 1];
}
if (i - 5 > 0) {
ans[i] += ans[i - 5];
}
if (i - 10 > 0) {
ans[i] += ans[i - 10];
}
}
return ans[x];
}
// correct
public int ways(int[] coins, int x) {
return ways(coins, coins.length, x);
}
public int ways(int[] coins, int m, int n) {
int[][] ans = new int[n + 1][m];
for (int i = 0; i < m; ++i) {
ans[0][i] = 1;
}
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < m; j++) {
final int withCoinJ = (i - coins[j] >= 0)? ans[i - coins[j]][j]: 0;
final int withoutCoinJ = (j >= 1) ? ans[i][j - 1]: 0;
ans[i][j] = withCoinJ + withoutCoinJ;
}
}
return ans[n][m - 1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment