The problem is from leetcode (link - https://leetcode.com/problems/the-number-of-ways-to-make-the-sum/description/ )
You have an infinite number of coins with values 1, 2, and 6, and only 2 coins with value 4.
Given an integer n, return the number of ways to make the sum of n with the coins you have.
Since the answer may be very large, return it modulo 109 + 7.
Note that the order of the coins doesn't matter and [2, 2, 3] is the same as [2, 3, 2].
Example 1:
Input: n = 4
Output: 4
Explanation:
Here are the four combinations: [1, 1, 1, 1], [1, 1, 2], [2, 2], [4].
Constraints 1 <= n <= 10^5
While i wrote the solution as
vector<int> temp{1,2,6};
class Solution {
public:
long long getTotalNumberOfWays(int n,int index,vector<vector<long long>>& dp){
if(n==0){
return 1;
}
if(n<0 || index>2){
return 0;
}
if(dp[index][n]!=-1){
return dp[index][n];
}
long long totalWaysWithoutFour = 0;
int newN = n;
while(newN>=0){
totalWaysWithoutFour += getTotalNumberOfWays(newN,index+1,dp);
newN-=temp[index];
}
return dp[index][n] = totalWaysWithoutFour;
}
int numberOfWays(int n) {
vector<vector<long long>> dp(3,vector<long long>(n+1,-1));
return (int)(getTotalNumberOfWays(n,0,dp) + getTotalNumberOfWays(n-4,0,dp) + getTotalNumberOfWays(n-8,0,dp))%((long long)pow(10,9)+7);
}
};
I am getting timeout on above code . While if i do this
vector<int> temp{1,2,6};
class Solution {
public:
long long getTotalNumberOfWays(int n,int index,vector<vector<long long>>& dp){
if(n==0){
return 1;
}
if(n<0 || index>2){
return 0;
}
if(dp[index][n]!=-1){
return dp[index][n];
}
long long totalWaysWithoutFour = 0;
return dp[index][n] = ((getTotalNumberOfWays(n-temp[index],index,dp)) + (getTotalNumberOfWays(n,index+1,dp)));
}
int numberOfWays(int n) {
vector<vector<long long>> dp(3,vector<long long>(n+1,-1));
return (getTotalNumberOfWays(n,0,dp) + getTotalNumberOfWays(n-4,0,dp) + getTotalNumberOfWays(n-8,0,dp))%((long long)(pow(10,9)+7));
}
};
The code is passing fine . My understanding was 1st and second code have same time complexity Am i wrong in this assumption if not than why is the first one timing out .
while(newN>=0)
-loop which most likely has a different complexity than the 2 recursive calls in the 2nd algorithm. Of cause this must be analyzed further to be certain.