Lab 10 - Ans
Lab 10 - Ans
Exercise 1:
Input: sum = 4, coins[] = {1,2,3},
Answer:
Output: 4
Explanation: there are four solutions: {1, 1, 1, 1}, {1, 1, 2}, {2, 2}, {1, 3}.
Exercise 2:
Input: sum = 10, coins[] = {2, 5, 3, 6}
Answer:
Output: 5
Explanation: There are five solutions:
{2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}.
Recursive solution:
count(coins,n,sum) = count(coins,n,sum-count[n-1]) + count(coins,n-1,sum)
For each coin, there are 2 options.
- Include the current coin: Subtract the current coin’s denomination from the
target sum and call the count function recursively with the updated sum and
the same set of coins i.e., count(coins, n, sum – coins[n-1] )
- Exclude the current coin: Call the count function recursively with the same
sum and the remaining coins. i.e., count(coins, n-1,sum ).
The final result will be the sum of both cases.
Time Complexity: O(2sum)
Exercise 3: ask students to implement the recursive solution above, considering
base case and recursive case. (Students can use any language they want)
Answer:
// Recursive C++ program for
// coin change problem.
#include <bits/stdc++.h>
using namespace std;
// Driver code
int main()
{
int i, j;
int coins[] = { 1, 2, 3 };
int n = sizeof(coins) / sizeof(coins[0]);
int sum = 5;
return 0;
}
// Driver Code
int main()
{
vector<int> coins{ 1, 2, 3 };
int n = 3;
int sum = 5;
cout << count(coins, n, sum);
return 0;
}