My LeetCode Diary - Day25 BackTracking
216. Combination Sum III
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backTracking(n,0,k,1);
return result;
}
void backTracking(int n, int sum, int k, int startIndex) {
if (path.size() == k) {
if (sum == n) {
result.add(new ArrayList<>(path));
}
}
if (sum > n) {
return;
}
for (int i = startIndex; i <= 9; i++) {
path.add(i);
sum += i;
backTracking(n, sum, k, i+1);
sum -= i;
path.removeLast();
}
}
}
17. Letter Combinations of a Phone Number
class Solution {
List<String> list = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return list;
}
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
backTracking(digits, numString, 0);
return list;
}
StringBuilder temp = new StringBuilder();
void backTracking( String digits, String[] numString, int index) {
if (index == digits.length()) {
list.add(temp.toString());
return;
}
String str = numString[(digits.charAt(index))-'0'];
for (int i = 0; i < str.length(); i++) {
temp.append(str.charAt(i));
backTracking(digits, numString, index + 1);
temp.deleteCharAt(temp.length() -1 );
}
}
}