File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
Algorithms/Medium/494_TargetSum Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments