vector<int> diffWaysToCompute2(vector<int>& nums,int beg,int end,vector<char>& opts) { vector<int> ans; if(beg==end){ ans.push_back(nums[beg]); return ans; } for(int j=beg;j<end;j++){ vector<int> a=diffWaysToCompute2(nums,beg,j,opts); vector<int> b=diffWaysToCompute2(nums,j+1,end,opts); for(int x=0;x<a.size();x++){ for(int y=0;y<b.size();y++){ switch(opts[j]){ case '+': ans.push_back(a[x]+b[y]); break; case '-': ans.push_back(a[x]-b[y]); break; case '*': ans.push_back(a[x]*b[y]); break; } } } } return ans; }
int* diffWaysToCompute(char* input, int* returnSize) { IntArray operands = int_array(); IntArray operators = int_array(); int count = 0; /* normalize the string into operands and operators */ normalize(input, &operands, &operators, &count); /* use the normalized data to compute */ int* result = diffWaysToCompute2(&operands, &operators, count, 0, returnSize); int_array_free(&operands); int_array_free(&operators); return result; }
vector<int> diffWaysToCompute(string input) { vector<int> nums; vector<int> ans; vector<char> opts; int i=0; while(1){ int n=0; while(i<input.size()&&isdigit(input[i])){ n=n*10+input[i]-'0'; i++; } nums.push_back(n); if(i==input.size()){ break; } opts.push_back(input[i++]); } ans=diffWaysToCompute2(nums,0,nums.size()-1,opts); return ans; }
int* diffWaysToCompute2(IntArray* operands, IntArray* operators, int size, int pos, int* returnSize) { int count = 0; IntArray result = int_array(); if (size == 0) { /* single operator */ int_array_set(&result, count++, operands->array[0]); } else { /* recursion, add parenthese at each operator position */ for (int i = pos; i < size; ++i) { int op = operators->array[i]; int lv = operands->array[i]; int rv = operands->array[i + 1]; int value = 0; if (op == '+') { value = lv + rv; } else if (op == '-') { value = lv - rv; } else { value = lv * rv; } IntArray new_operands = int_array_rm(operands, size + 1, i); IntArray new_operators = int_array_rm(operators, size, i); int_array_set(&new_operands, i, value); int sub_size; int* sub = diffWaysToCompute2(&new_operands, &new_operators, size - 1, i == 0 ? 0 : i - 1, &sub_size); for (int j = 0; j < sub_size; ++j) { int_array_set(&result, count++, sub[j]); } free(sub); } } *returnSize = count; return result.array; }