Problem Description
Given an integer array, write a program to determine whether it can be divided into two subsets with equal sums.
This problem is known as the ‘Subset Sum Problem’. It can be solved using Dynamic Programming.
Input Format
- The first line contains the size of the array N (1 ≤ N ≤ 20).
- The second line contains N integers of the array (each integer is between 0 and 10000).
Output Format
If it is possible to partition the subsets, print “YES”; otherwise, print “NO”.
Example Input
4 1 5 11 5
Example Output
YES
Approach to Solve the Problem
To solve this problem, you should follow these steps:
- Calculate the sum of the input array.
- If the sum is odd, it is impossible for the two subsets to have equal sums, so return “NO”.
- If the sum is even, set the target value to half of the sum and use dynamic programming to determine if it can be achieved.
- Set up a state table and check if each number can be used to form the target value.
C++ Code
#include <iostream> #include <vector> using namespace std; bool canPartition(vector<int>& arr) { int sum = 0; for (int num : arr) sum += num; if (sum % 2 != 0) return false; int target = sum / 2; vector<bool> dp(target + 1, false); dp[0] = true; for (int num : arr) { for (int j = target; j >= num; j--) { dp[j] = dp[j] || dp[j - num]; } } return dp[target]; } int main() { int N; cin >> N; vector<int> arr(N); for (int i = 0; i < N; i++) { cin >> arr[i]; } cout << (canPartition(arr) ? "YES" : "NO") << endl; return 0; }
Code Explanation
The above code works as follows:
- First, it calculates the total sum of the number array.
- It checks if the sum is odd. If it is odd, it returns “NO”.
- If the sum is even, it sets the target value to half of the sum and initializes the dynamic programming array.
- By iterating through each number, it checks if it can create the target value.
- Ultimately, it prints “YES” if the target value can be created; otherwise, it prints “NO”.
Time Complexity
The time complexity of this algorithm is O(N * target), where N is the number of input numbers and target is half of the total sum of the input array. This determines the number of operations that can be used to create different subsets.
Conclusion
This concludes the code and explanation for the Subset Sum Problem. Such algorithmic problems often appear in coding tests, so it is good to practice them frequently. In the next lecture, we will cover more complex problems and their solutions.
Questions and Feedback
If you have any questions about the code you wrote or any parts you find difficult to understand, feel free to leave a comment!