Movatterモバイル変換


[0]ホーム

URL:


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

Commit283b874

Browse files
committed
Added 3 solutions
1 parent56b9a57 commit283b874

File tree

3 files changed

+86
-0
lines changed

3 files changed

+86
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
classSolution {
11+
publicTreeNodelowestCommonAncestor(TreeNoderoot,TreeNodep,TreeNodeq) {
12+
if (root ==null ||root ==p ||root ==q) {
13+
returnroot;
14+
}
15+
16+
TreeNodeleft =lowestCommonAncestor(root.left,p,q);
17+
TreeNoderight =lowestCommonAncestor(root.right,p,q);
18+
19+
if (left !=null &&right !=null) {
20+
returnroot;
21+
}
22+
23+
returnleft !=null ?left :right;
24+
}
25+
}

‎Medium/Minimum Path Sum.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
classSolution {
2+
publicstaticintminPathSum(int[][]grid) {
3+
intm =grid.length;
4+
intn =grid[0].length;
5+
6+
for (inti=0;i<m;i++) {
7+
for (intj=0;j<n;j++) {
8+
if (i ==0 &&j !=0) {
9+
grid[i][j] +=grid[i][j-1];
10+
}
11+
if (i !=0 &&j ==0) {
12+
grid[i][j] +=grid[i-1][j];
13+
}
14+
if (i !=0 &&j !=0) {
15+
grid[i][j] +=Math.min(grid[i-1][j],grid[i][j-1]);
16+
}
17+
}
18+
}
19+
20+
returngrid[m-1][n-1];
21+
}
22+
}

‎Medium/Path Sum II.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
classSolution {
11+
List<List<Integer>>list =newArrayList<>();
12+
publicList<List<Integer>>pathSum(TreeNoderoot,intsum) {
13+
if (root ==null)returnlist;
14+
15+
Stack<Integer>path =newStack<>();
16+
17+
pathSumImpl(root,sum,path);
18+
returnlist;
19+
}
20+
21+
privatevoidpathSumImpl(TreeNoderoot,intsum,Stack<Integer>path) {
22+
path.push(root.val);
23+
if (root.left ==null &&root.right ==null) {
24+
if (sum ==root.val) {
25+
list.add(newArrayList<Integer>(path));
26+
}
27+
}
28+
29+
if (root.left !=null) {
30+
pathSumImpl(root.left,sum-root.val,path);
31+
}
32+
33+
if (root.right !=null) {
34+
pathSumImpl(root.right,sum-root.val,path);
35+
}
36+
37+
path.pop();
38+
}
39+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp