Skip to content

Commit 9a650fc

Browse files
authored
Create 02 - Bottom-Up | DP | Approach.cpp
1 parent 05a988f commit 9a650fc

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public:
3+
// Function to calculate the number of combinations using dynamic programming
4+
int solve(vector<int>& nums, int target) {
5+
// Edge case: If the target is negative or the input array is empty, return 0
6+
if(target < 0 || nums.empty()) return 0;
7+
8+
// Create a DP array to store the number of ways to achieve each target sum
9+
vector<int> dp(target + 1, 0);
10+
11+
// Base case: There's only one way to make a sum of 0 (choose nothing)
12+
dp[0] = 1;
13+
14+
// Iterate over all possible target values from 1 to the given target
15+
for(int currentTarget = 1; currentTarget <= target; currentTarget++) {
16+
// Iterate through each number in the input array
17+
for(int numIndex = 0; numIndex < nums.size(); numIndex++) {
18+
// Check if the current number can contribute to the current target
19+
if(currentTarget - nums[numIndex] >= 0) {
20+
// Handle potential integer overflow
21+
if (dp[currentTarget] > INT_MAX - dp[currentTarget - nums[numIndex]]) {
22+
dp[currentTarget] = INT_MAX; // Set to INT_MAX if overflow occurs
23+
} else {
24+
// Update dp[currentTarget] by adding the ways to achieve the reduced target
25+
dp[currentTarget] += dp[currentTarget - nums[numIndex]];
26+
}
27+
}
28+
}
29+
}
30+
31+
// Return the number of combinations to make the target sum
32+
return dp[target];
33+
}
34+
35+
// Main function to calculate the number of combinations
36+
int combinationSum4(vector<int>& nums, int target) {
37+
// Call the DP-based solve function
38+
return solve(nums, target);
39+
}
40+
};

0 commit comments

Comments
 (0)