Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ce42031

Browse files
Added LC 494 java solution (#144)
1 parent e045075 commit ce42031

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
int[] nums;
3+
int n, target;
4+
HashMap<ArrayList<Integer>, Integer> dp = new HashMap<>();
5+
6+
private int solve(int pos, int sum) {
7+
ArrayList<Integer> aList = new ArrayList<>();
8+
aList.add(pos);
9+
aList.add(sum);
10+
11+
if (pos >= n) {
12+
if (sum == target) {
13+
return 1;
14+
}
15+
16+
return 0;
17+
} else if (dp.containsKey(aList)) {
18+
return dp.get(aList);
19+
} else {
20+
int ans = solve(pos + 1, sum + nums[pos]);
21+
ans += solve(pos + 1, sum - nums[pos]);
22+
dp.put(aList, ans);
23+
24+
return ans;
25+
}
26+
}
27+
28+
public int findTargetSumWays(int[] nums, int target) {
29+
this.nums = nums;
30+
n = nums.length;
31+
this.target = target;
32+
33+
return solve(1, nums[0]) + solve(1, -nums[0]);
34+
}
35+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /