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
| #include <vector> using namespace std; int NUM[20],tot = 0,T, size;
vector<int> DP(1048576,-1); int dp(int idx,int bit_mask){ if(idx==size) return 0; if(DP[bit_mask]!=-1) return DP[bit_mask]; if(bit_mask&1<<idx){ DP[bit_mask] = dp(idx+1,bit_mask^1<<idx) - 2*NUM[idx]; return DP[bit_mask]; } return dp(idx+1,bit_mask); }
int DFS(int idx,int bit_mask){ if(idx==size){ if(T == tot + dp(0,bit_mask)) return 1; return 0; } return DFS(idx+1,bit_mask)+DFS(idx+1,bit_mask|1<<idx); }
int solution(vector<int> numbers, int target) { T = target; size = numbers.size(); for(int i=0;i<numbers.size();i++) tot += NUM[i] = numbers[i]; return DFS(0,0); }
|