Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit aa43937

Browse files
authored
Merge pull request #373 from evaunit00/main
Added question 17 and 39 in Java
2 parents 19c46e4 + 9d8b53a commit aa43937

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
import java.util.Map;
4+
5+
class Solution {
6+
private Map<Character, String> digitToChar = Map.of(
7+
'2', "abc", '3', "def", '4', "ghi", '5', "jkl",
8+
'6', "mno", '7', "pqrs", '8', "tuv", '9', "wxyz");
9+
10+
public List<String> letterCombinations(String digits) {
11+
12+
if (digits.length() == 0) {
13+
return new ArrayList();
14+
}
15+
16+
List<String> ans = new ArrayList();
17+
String cur = "";
18+
backtrack(digits, ans, cur, 0);
19+
return ans;
20+
21+
}
22+
23+
public void backtrack(String digits, List<String> ans, String cur, int index) {
24+
25+
if (cur.length() == digits.length()) {
26+
ans.add(cur);
27+
return;
28+
} else if (index >= digits.length()) {
29+
return;
30+
} else {
31+
String digit = digitToChar.get(digits.charAt(index));
32+
for (char c : digit.toCharArray()) {
33+
backtrack(digits, ans, cur + c, index + 1);
34+
}
35+
}
36+
}
37+
}

java/39-Combination-Sum.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
3+
List<List<Integer>> ans = new ArrayList<List<Integer>>();
4+
List<Integer> cur = new ArrayList();
5+
backtrack(candidates, target, ans, cur, 0);
6+
return ans;
7+
8+
}
9+
10+
public void backtrack(int[] candidates, int target, List<List<Integer>> ans, List<Integer> cur, int index) {
11+
if (target == 0) {
12+
ans.add(new ArrayList(cur));
13+
} else if (target < 0 || index >= candidates.length) {
14+
return;
15+
} else {
16+
cur.add(candidates[index]);
17+
backtrack(candidates, target - candidates[index], ans, cur, index);
18+
19+
cur.remove(cur.get(cur.size() - 1));
20+
backtrack(candidates, target, ans, cur, index + 1);
21+
}
22+
23+
}
24+
}

0 commit comments

Comments
 (0)