-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbalanced_partition.cpp
More file actions
45 lines (36 loc) · 971 Bytes
/
balanced_partition.cpp
File metadata and controls
45 lines (36 loc) · 971 Bytes
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
/**
* Author: Skylar Payne
* Date: January 1, 2015
* Determine if there is a balanced partition of a given array
**/
#include <iostream>
#include <vector>
#include <stdlib.h>
bool balanced_partition(std::vector<int> const& a) {
int sum = 0;
for(int i = 0; i < a.size(); ++i) {
sum += a[i];
}
if(sum % 2 == 1) {
return false;
}
std::vector<std::vector<bool> > mem(a.size() + 1, std::vector<bool>(sum / 2 + 1, false));
for(int j = 0; j < mem[0].size(); ++j) {
for(int i = 1; i < mem.size(); ++i) {
mem[i][j] = ((a[i-1] == j) || (mem[i-1][j]) || (j - a[i-1] >= 0 ? mem[i-1][j-a[i-1]] : false));
}
}
return mem[a.size()][sum / 2];
}
int main(int argc, char** argv) {
if(argc < 2) {
std::cout << "Please provide a list of integers" << std::endl;
return -1;
}
std::vector<int> a(argc - 1);
for(int i = 1; i < argc; ++i) {
a[i-1] = atoi(argv[i]);
}
std::cout << (balanced_partition(a) ? "true" : "false") << std::endl;
return 0;
}