Skip to content

Commit 9667b77

Browse files
committed
DP partition problem added.
1 parent 4b14ead commit 9667b77

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

DP/PartitionProblem/partition.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
Given a set of positive integers, find if it can be divided into two subsets with equal sum.
3+
Partition problem is special case of Subset Sum Problem which itself is a special case of the Knapsack Problem.
4+
The idea is to calculate sum of all elements in the set.
5+
*/
6+
7+
#include <iostream>
8+
#include <string>
9+
using namespace std;
10+
11+
// Return true if there exists a subset of arr[] with given sum
12+
bool subsetSum(int arr[], int n, int sum)
13+
{
14+
// return true if sum becomes 0 (subset found)
15+
if (sum == 0)
16+
return true;
17+
18+
// base case: no items left or sum becomes negative
19+
if (n < 0 || sum < 0)
20+
return false;
21+
22+
// Case 1. include current item in the subset (arr[n]) and recurse
23+
// for remaining items (n - 1) with remaining sum (sum - arr[n])
24+
bool include = subsetSum(arr, n - 1, sum - arr[n]);
25+
26+
// Case 2. exclude current item n from subset and recurse for
27+
// remaining items (n - 1)
28+
bool exclude = subsetSum(arr, n - 1, sum);
29+
30+
// return true if we get subset by including or excluding current item
31+
return include || exclude;
32+
}
33+
34+
// Return true if given array arr[0..n-1] can be divided into two
35+
// subsets with equal sum
36+
bool partition(int arr[], int n)
37+
{
38+
int sum = 0;
39+
for (int i = 0; i < n; i++)
40+
sum += arr[i];
41+
42+
// return true if sum is even and array can can be divided into
43+
// two subsets with equal sum
44+
return !(sum & 1) && subsetSum(arr, n - 1, sum/2);
45+
}
46+
47+
// main function to solve partition problem
48+
int main()
49+
{
50+
// Input: set of items
51+
int arr[] = { 7, 3, 1, 5, 4, 8 };
52+
53+
// number of items
54+
int n = sizeof(arr) / sizeof(arr[0]);
55+
56+
if (partition(arr, n))
57+
cout << "Yes";
58+
else
59+
cout << "No";
60+
61+
return 0;
62+
}

0 commit comments

Comments
 (0)