Skip to content

Commit d1b0282

Browse files
committed
Added 2 solutions
1 parent 4f6ca29 commit d1b0282

2 files changed

Lines changed: 94 additions & 0 deletions

File tree

Medium/Combinations.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public List<List<Integer>> combine(int n, int k) {
3+
List<Integer> temp = new ArrayList<>();
4+
List<List<Integer>> ans = new ArrayList<>();
5+
helper(n, 1, temp, ans, k);
6+
7+
return ans;
8+
}
9+
10+
private void helper(int n, int start, List<Integer> temp, List<List<Integer>> ans, int len) {
11+
if (temp.size() == len) {
12+
ans.add(new ArrayList<>(temp));
13+
return;
14+
}
15+
16+
for (int i=start; i<=n; i++) {
17+
// Choose
18+
temp.add(i);
19+
20+
// Explore
21+
helper(n, i+1, temp, ans, len);
22+
23+
// Un-choose
24+
temp.remove(temp.size() - 1);
25+
}
26+
}
27+
}

Medium/Diagonal Traverse.java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class Solution {
2+
public int[] findDiagonalOrder(int[][] matrix) {
3+
if (matrix.length == 0 || matrix[0].length == 0) {
4+
return new int[]{};
5+
}
6+
7+
int[] ans = new int[matrix.length * matrix[0].length];
8+
int idx = 0;
9+
10+
int i = 0;
11+
boolean up = true;
12+
13+
// First Triangle
14+
while (i < matrix.length) {
15+
int j = 0;
16+
int tempI = i;
17+
List<Integer> temp = new ArrayList<>();
18+
while (j < matrix[0].length && tempI >= 0) {
19+
temp.add(matrix[tempI][j]);
20+
j++;
21+
tempI--;
22+
}
23+
24+
if (!up) {
25+
Collections.reverse(temp);
26+
}
27+
28+
for (int num : temp) {
29+
ans[idx++] = num;
30+
}
31+
32+
up = !up;
33+
i++;
34+
}
35+
36+
if (matrix[i-1].length < 2) {
37+
return ans;
38+
}
39+
40+
i--;
41+
int j = 1;
42+
// Second Triangle
43+
while (j < matrix[0].length) {
44+
int k = i;
45+
List<Integer> temp = new ArrayList<>();
46+
int tempJ = j;
47+
while (k >= 0 && tempJ < matrix[0].length) {
48+
temp.add(matrix[k][tempJ]);
49+
k--;
50+
tempJ++;
51+
}
52+
53+
if (!up) {
54+
Collections.reverse(temp);
55+
}
56+
57+
for (int num : temp) {
58+
ans[idx++] = num;
59+
}
60+
61+
up = !up;
62+
j++;
63+
}
64+
65+
return ans;
66+
}
67+
}

0 commit comments

Comments
 (0)