Skip to content

Added LC 494 java solution #144

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 14, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Algorithms/Medium/494_TargetSum/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Solution {
int[] nums;
int n, target;
HashMap<ArrayList<Integer>, Integer> dp = new HashMap<>();

private int solve(int pos, int sum) {
ArrayList<Integer> aList = new ArrayList<>();
aList.add(pos);
aList.add(sum);

if (pos >= n) {
if (sum == target) {
return 1;
}

return 0;
} else if (dp.containsKey(aList)) {
return dp.get(aList);
} else {
int ans = solve(pos + 1, sum + nums[pos]);
ans += solve(pos + 1, sum - nums[pos]);
dp.put(aList, ans);

return ans;
}
}

public int findTargetSumWays(int[] nums, int target) {
this.nums = nums;
n = nums.length;
this.target = target;

return solve(1, nums[0]) + solve(1, -nums[0]);
}
}