@@ -50,18 +50,132 @@ The path sum is (3 + 1) = 4.
50
50
51
51
## Solutions
52
52
53
+ DFS.
54
+
53
55
<!-- tabs:start -->
54
56
55
57
### ** Python3**
56
58
57
59
``` python
58
-
60
+ class Solution :
61
+ def pathSum (self , nums : List[int ]) -> int :
62
+ def dfs (node , t ):
63
+ if node not in mp:
64
+ return
65
+ t += mp[node]
66
+ d, p = divmod (node, 10 )
67
+ l = (d + 1 ) * 10 + (p * 2 ) - 1
68
+ r = l + 1
69
+ nonlocal ans
70
+ if l not in mp and r not in mp:
71
+ ans += t
72
+ return
73
+ dfs(l, t)
74
+ dfs(r, t)
75
+
76
+ ans = 0
77
+ mp = {num // 10 : num % 10 for num in nums}
78
+ dfs(11 , 0 )
79
+ return ans
59
80
```
60
81
61
82
### ** Java**
62
83
63
84
``` java
85
+ class Solution {
86
+ private int ans;
87
+ private Map<Integer , Integer > mp;
88
+
89
+ public int pathSum (int [] nums ) {
90
+ ans = 0 ;
91
+ mp = new HashMap<> (nums. length);
92
+ for (int num : nums) {
93
+ mp. put(num / 10 , num % 10 );
94
+ }
95
+ dfs(11 , 0 );
96
+ return ans;
97
+ }
98
+
99
+ private void dfs (int node , int t ) {
100
+ if (! mp. containsKey(node)) {
101
+ return ;
102
+ }
103
+ t += mp. get(node);
104
+ int d = node / 10 , p = node % 10 ;
105
+ int l = (d + 1 ) * 10 + (p * 2 ) - 1 ;
106
+ int r = l + 1 ;
107
+ if (! mp. containsKey(l) && ! mp. containsKey(r)) {
108
+ ans += t;
109
+ return ;
110
+ }
111
+ dfs(l, t);
112
+ dfs(r, t);
113
+ }
114
+ }
115
+ ```
116
+
117
+ ### ** C++**
118
+
119
+ ``` cpp
120
+ class Solution {
121
+ public:
122
+ int ans;
123
+ unordered_map<int, int> mp;
124
+
125
+ int pathSum(vector<int>& nums) {
126
+ ans = 0;
127
+ mp.clear();
128
+ for (int num : nums) mp[num / 10] = num % 10;
129
+ dfs(11, 0);
130
+ return ans;
131
+ }
132
+
133
+ void dfs (int node, int t) {
134
+ if (!mp.count(node)) return;
135
+ t += mp[ node] ;
136
+ int d = node / 10, p = node % 10;
137
+ int l = (d + 1) * 10 + (p * 2) - 1;
138
+ int r = l + 1;
139
+ if (!mp.count(l) && !mp.count(r))
140
+ {
141
+ ans += t;
142
+ return;
143
+ }
144
+ dfs(l, t);
145
+ dfs(r, t);
146
+ }
147
+ };
148
+ ```
64
149
150
+ ### **Go**
151
+
152
+ ```go
153
+ func pathSum(nums []int) int {
154
+ ans := 0
155
+ mp := make(map[int]int)
156
+ for _, num := range nums {
157
+ mp[num/10] = num % 10
158
+ }
159
+ var dfs func(node, t int)
160
+ dfs = func(node, t int) {
161
+ if v, ok := mp[node]; ok {
162
+ t += v
163
+ d, p := node/10, node%10
164
+ l := (d+1)*10 + (p * 2) - 1
165
+ r := l + 1
166
+ if _, ok1 := mp[l]; !ok1 {
167
+ if _, ok2 := mp[r]; !ok2 {
168
+ ans += t
169
+ return
170
+ }
171
+ }
172
+ dfs(l, t)
173
+ dfs(r, t)
174
+ }
175
+ }
176
+ dfs(11, 0)
177
+ return ans
178
+ }
65
179
```
66
180
67
181
### ** ...**
0 commit comments