- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Partition Equal Subset Sum in C++
Suppose we have a non-empty array containing only positive numbers, we have to find if the array can be partitioned into two subsets such that the sum of elements in both subsets is the same. So if the input is like [1,5,11,5], the output will be true. As this array can be partitioned as [1, 5, 5] and [11]
To solve this, we will follow these steps −
- n := size of the array
- sum := 0
- for i := 0 to n – 1
- sum := sum + nums[i]
- if sum is odd, return false
- sum := sum / 2
- create one array called dp of size sum + 1
- dp[0] := true
- for i in range 0 to n – 1
- x := nums[i]
- for j := sum down to j – x
- dp[j] := dp[j] or dp[j - x], which is not 0
- return dp[sum]
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: bool canPartition(vector<int>& nums) { int n = nums.size(); int sum = 0; for(int i =0;i<n;i++)sum+=nums[i]; if(sum&1)return false; sum/=2; vector <bool> dp(sum+1); dp[0] = true; for(int i =0;i<n;i++){ int x = nums[i]; for(int j =sum;j-x>=0;j--){ dp[j]=dp[j] || dp[j-x]; } } return dp[sum]; } }; main(){ Solution ob; vector<int> v = {1,5,11,5}; cout << ob.canPartition(v); }
Input
[1,5,11,5]
Output
1
- Related Articles
- Partition to K Equal Sum Subsets in C++
- Equal Tree Partition in C++
- Partition Array Into Three Parts With Equal Sum in Python
- Program to check whether we can partition a list with k-partitions of equal sum in C++
- Check if it possible to partition in k subarrays with equal sum in Python
- Sum of subset differences in C++
- Maximum average sum partition of an array in C++
- C / C++ Program for Subset Sum (Backtracking)
- Maximum size subset with given sum in C++
- Partition Array for Maximum Sum in Python
- Maximum subset with bitwise OR equal to k in C++
- Subset Sum Problem
- Equal partition of an array of numbers - JavaScript
- Partition List in C++
- Partition Labels in C++

Advertisements