Use sets to keep unique and Binary Form 1111 to the possible results. The code is :
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
class Solution {
public:
set<double> status[16];
typedef set<double>::iterator ITER;
void f(int x, vector<int>& vec) {
for (int i = 1; i <= x / 2; ++i) {
if ((x & i) == i) {
for (ITER j = status[i].begin(); j != status[i].end(); ++j)
for (ITER k = status[x-i].begin(); k != status[x-i].end(); ++k) {
status[x].insert((*j) * (*k));
status[x].insert((*j) + (*k));
status[x].insert((*j) - (*k));
status[x].insert((*k) - (*j));
if ((*k) != 0)
status[x].insert((*j) / (*k));
if ((*j) != 0)
status[x].insert((*k) / (*j));
}
}
}
}
void init(const vector<int>& vec) {
for (int i = 0; i < vec.size(); ++i)
status[(1 << i)].insert((double)vec[i]);
}
bool getSum24(vector<int>& vec) {
init(vec);
for (int i = 1; i <= 15; ++i)
f(i, vec);
return status[15].find(24) != status[15].end() ? true : false;
}
};
int main() {
int a[] = {1, 1, 1, 1};
Solution s;
vector<int> vec(a, a+4);
bool res = s.getSum24(vec);
return 0;
}
import math
class Test:
def Sum24(self, nums):
self.status = {i: set() for i in range(1, 16)}
for i in range(4):
self.status[1<<i].add(nums[i])
for groupindex in range(1,16):
for i in range(1, math.ceil((groupindex+1)/2)):
if (i & groupindex == i):
subgroupindex = i
relativegroupindex = groupindex -subgroupindex
for k in self.status[subgroupindex]:
for l in self.status[relativegroupindex]:
self.status[groupindex].add(k + l)
self.status[groupindex].add(k - l)
self.status[groupindex].add(l - k)
self.status[groupindex].add(k * l)
if (k != 0):
self.status[groupindex].add(l / k)
if (l != 0):
self.status[groupindex].add(k / l)
return self.status
test = Test()
res = test.Sum24([1,1,1,1])
print(24 in res[15])