-
Notifications
You must be signed in to change notification settings - Fork 0
/
Perfect Sum Problem.cpp
104 lines (78 loc) · 3.22 KB
/
Perfect Sum Problem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
Problem Link: https://practice.geeksforgeeks.org/problems/perfect-sum-problem5633/1
*/
// -----Approach 1: Memoization ------------------------------------------------------------\
class Solution{
private:
int mod= 1e9+7; // 1000000007;
int sol(int idx, int sum, vector<vector<int>>& dp, vector<int>& arr){
if(sum == 0) return 1;
if(idx == 0) return (arr[0] == sum);
if(dp[idx][sum] != -1) return dp[idx][sum];
int notPick= sol(idx-1, sum, dp, arr)%mod;
int pick= 0;
if(arr[idx] <= sum) pick= sol(idx-1, sum - arr[idx], dp, arr)%mod;
return dp[idx][sum] = ((pick + notPick)%mod);
}
public:
int perfectSum(int arr[], int n, int sum)
{
// Your code goes here
vector<int> temp;
int cntZero = 0;
for(int i = 0; i < n; i++)
if(arr[i] != 0) temp.push_back(arr[i]);
else cntZero++; // array can include zero so use different logic to handle this
int size = temp.size();
vector<vector<int>> dp(size, vector<int> (sum+1, -1));
int mult = (int)(pow(2, cntZero))%mod; // we can calculate the no of combinations if there are n zeros, just 2*n with the result
return ( ( sol(size-1, sum, dp, temp)*mult )%mod );
}
};
// -----Approach 2: Memoization ------------------------------------------------------------\
class Solution{
private:
int mod= 1e9+7; // 1000000007;
int sol(int idx, int sum, vector<vector<int>>& dp, int arr[]){
if(idx == 0){
if(sum == 0 && arr[0] == 0) return 2;
if(sum ==0 || sum == arr[0]) return 1;
return 0;
}
if(dp[idx][sum] != -1) return dp[idx][sum];
int notPick= sol(idx-1, sum, dp, arr)%mod;
int pick= 0;
if(arr[idx] <= sum) pick= sol(idx-1, sum - arr[idx], dp, arr)%mod;
return dp[idx][sum] = ((pick + notPick)%mod);
}
public:
int perfectSum(int arr[], int n, int sum)
{
// Your code goes here
vector<vector<int>> dp(n, vector<int> (sum+1, -1));
return sol(n-1, sum, dp, arr)%mod;
}
};
// -----Approach 3: Tabulation ------------------------------------------------------------\
class Solution{
public:
int perfectSum(int arr[], int n, int sum)
{
// Your code goes here
int mod = 1e9+7;
int dp[n+1][sum+1];
for(int i=0; i<n+1; i++) dp[i][0]=1;
for(int j=1; j<sum+1; j++) dp[0][j]=0;
for(int i=1; i<n+1; i++){
for(int s=0; s<=sum; s++){
if(arr[i-1] <= s){
dp[i][s]= (dp[i-1][s-arr[i-1]] + dp[i-1][s])%mod;
}
else{
dp[i][s]=(dp[i-1][s]) %mod;
}
}
}
return dp[n][sum];
}
};