auto optimize_cpp_stdio = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return0; }(); classSolution { public: conststaticint maxn = 1e5 + 10; conststaticint maxm = 1e5 + 10; constint INF = 0x3f3f3f3f; intfindTargetSumWays(vector<int> &nums, int target) { // sum - 2x = target, x = (sum-target)/2 int sum = 0; for (auto &x : nums) sum += x; if ((sum - target) < 0 || (sum - target) & 1) return0; return dfs(nums, target, sum, 0, 0); } intdfs(vector<int> &nums, int target, int extra, int sum, int step) { if(sum + extra < target || sum - extra > target) return0; if (step >= nums.size()) { if (sum == target) return1; else return0; }
int ans = 0; ans += dfs(nums, target, extra - nums[step], sum + nums[step], step + 1); ans += dfs(nums, target, extra - nums[step], sum - nums[step], step + 1); return ans; } };