I am learning dynamic programming and came across this famous coins change problem.
The reccurence relation to solve this problem is given by
countCoinsChangeRec(arr, sum - arr[i], i) + countCoinsChangeRec(arr, sum, i - 1);
The simplest way to optimize the problem is by storing the solutions of sub problem. So I maintained a Map
for each value of (sum,i)
. There by not solving same problems again.
String key = sum + ":" + i;
Integer memoizedVal = results.get(key);
if (memoizedVal != null) {
return memoizedVal;
}
Next level of optimization is having a 2D table of n X sum
where n is number of elements in the set.
It is easily understandable from reccurence relation that (arr, sum - arr[i], i)
translates to DP[sum-arr[i]]
in same row.(Because i
is same)
And (arr, sum, i - 1)
translates to DP[i-1]
(Previous row in sum
column).
Complete solution with 2D matrix shown below.
public static int countWaysDP2D(int[] arr, int sum) {
int[][] table = new int[arr.length][sum + 1];
table[0][0] = 1;
for (int i = 1; i <= sum; i++) {
table[0][i] = 0;
}
for (int j = 1; j < arr.length; j++) {
table[j][0] = 1;
}
for (int i = 1; i < arr.length; i++) {
for (int j = 1; j <= sum; j++) {
int sumWithI = j - arr[i-1] < 0 ? 0 : table[i][j - arr[i-1]];
int sumWithoutI = table[i - 1][j];
table[i][j] = sumWithI + sumWithoutI;
}
}
return table[arr.length - 1][sum];
}
But the soultion given here in method 2 uses just 1D array as shown below
public static int countWaysDP1D(int[] arr, int sum) {
int[] table = new int[sum + 1];
table[0] = 1;
for (int i = 0; i < arr.length; i++) {
for (int j = arr[i]; j <= sum; j++) {
table[j] += table[j - arr[i]];
}
}
return table[sum];
}
What is the logic behind using just 1D array? I tested with many input values and results were same as 2D array. How is 2D array solution converted to 1D array?
I mean where are all the initial conditions gone?(0th row
and 0th column
)
For j
th for loop, why does it iterate from j
th element in the array till sum
incremented by 1
? It is really hard to visualize all of that. Can somebody explain this transformation step by step?