-
Notifications
You must be signed in to change notification settings - Fork 160
/
Minimal subset sum.cpp
89 lines (48 loc) · 1.55 KB
/
Minimal subset sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Given a set of integer, you could apply sign operation to the integer, find
the minimum sum that is close to but no less than 0;
input 3 5 7 11 13
output 1
*/
/*
solution: dynamic programming. The problem transfers to partition the array to two parts such that their difference is as close as possible.
part[i][j]:true if a subset of {arr[0], arr[1], ..arr[j-1]} has sum equal to i, otherwise false
O(n*sum) time, O(n*sum) space
*/
#include<iostream>
using namespace std;
int FindPartiion(int arr[], int len) {
int sum = 0;
int i, j;
for (i = 0; i < len; ++i) {
sum += arr[i];
}
bool part[50][8];
for (i = 0; i <= len; ++i) {
part[0][i] = true;
}
for (i = 1; i <= sum/2; ++i) {
part[i][0] = false;
}
int largest = 0;
// Fill the partition table in botton up manner
for (i = 1; i <= sum/2; ++i) {
for (j = 1; j <= n; ++j) {
if (part[i][j-1]) { //not include arr[j]
part[i][j] = true ; largest = i;
}
if (i >= arr[j-1]) { //include arr[j]
if(part[i - arr[j-1]][j-1]) {
part[i][j] = true ; largest = i;
}
}
}
}
return sum - 2 * largest;
}
int main() {
int arr[5] = {3, 5, 7, 11, 13};
int len = sizeof(arr)/sizeof(arr[0]);
cout<<FindPartiion(arr,len)<<endl;
return 0;
}