Dynamicprogramming
Dynamicprogramming
Programming Approaches
Muhammad Tayyab, Faizan Rasool, Muhammad Shafqat,
Muhammad Ehtisham, Kiran Waheed, Aimen Nawaz
1 Problem Statement
Given a set of positive integers and a target sum, determine if there is a subset
of the given set with a sum equal to the target sum.
2 Constraints
• Each number in the set can be used only once.
• The subset sum should be exactly equal to the target sum.
3 Input
• An integer n representing the number of elements in the set.
• An integer target_sum representing the target sum.
4 Output
• A boolean indicating whether a subset with the target sum exists.
1
2. Check Sum: For each subset generated, calculate the sum of its elements.
3. Compare Sum: Compare the sum of each subset with the target sum.
4. Return Result: If any subset has a sum equal to the target sum, return
True; otherwise, return False.
5.2 Analysis
• Time Complexity: Generating all subsets requires examining 2n possi-
ble combinations, where n is the number of elements in the set. Calcu-
lating the sum for each subset takes O(n) time. Thus, the overall time
complexity is O(2n · n).
• Space Complexity: The brute force approach does not require addi-
tional space proportional to the input size beyond the input set itself, so
the space complexity is O(n).
3. State Transition: For each element of the set, iterate through the target
sum and update the DP table based on the inclusion or exclusion of the
current element.
4. Final Result: The value of DP[n][target_sum] indicates whether the
target sum can be achieved using all elements of the set.
6.3 Analysis
• Time Complexity: Constructing the DP table involves iterating through
all elements of the set (O(n)) and all possible sums up to the target sum
(O(target_sum)). Thus, the time complexity is O(n · target_sum).
Tayyab
• Space Complexity: The DP table requires space proportional to the
product of the number of elements in the set and the target sum, leading
to a space complexity of O(n · target_sum).
7 Conclusion
• Brute Force vs. Dynamic Programming: While the brute force
approach exhaustively explores all possible subsets, resulting in exponen-
tial time complexity, the dynamic programming approach optimally solves
the problem by leveraging solutions to subproblems, leading to polynomial
time complexity.
Tayyab