I was solving this(https://www.hackerrank.com/challenges/coin-change/copy-from/188149763) problem on Hackerrank
which can be summarized as follows :
Find the total number ways to exchange a certain value with the given set of coin denominations.
Here is my code which got accepted:
long getWays(int n, vector<long> c) {
long dp[n+1];
memset(dp, 0ll, sizeof(dp));
dp[0] = 1;
for(int ci=1; ci<=c.size(); ci++)
{
for(int i=1; i<=n; i++)
{
if(c[ci-1] > i) continue;
dp[i] += dp[i-c[ci-1]];
}
}
return dp[n];
}
Here n is the total value we are supposed to get and c is the array of coins. My question is if I reverse the order of loops i.e. do something like
long getWays(int n, vector<long> c) {
long dp[n+1];
memset(dp, 0ll, sizeof(dp));
dp[0] = 1;
for(int i=1; i<=n; i++){
for(int ci=1; ci<=c.size(); ci++)
{
if(c[ci-1] > i) continue;
dp[i] += dp[i-c[ci-1]];
}
}
return dp[n];
}
Why does the answer change?
long dp[n+1];
-- This is not valid C++. Valid C++ isstd::vector<long> dp(n+1,0);
, and then you don't need thatmemset
. - PaulMcKenziedp[i-c[ci-1]]
to calculatedp[i]
. It only works ifdp[i-c[ci-1]]
is already calculated. Therefore the order is important. - Thomas Sablik