216.组合总和III
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new LinkedList<>();
Stack<Integer> stack = new Stack<>();
process(res, stack, 1, 0, k, n);
return res;
}
public void process(List<List<Integer>> res, Stack<Integer> stack, int cur, int sum, int k, int n) {
if (sum == n && stack.size() == k) {
List<Integer> linkedList = new LinkedList<>();
Integer[] integers = stack.toArray(new Integer[stack.size()]);
linkedList = Arrays.asList(integers);
res.add(linkedList);
return;
}
for (int i = cur; i <= 9; i++) {
if (stack.size() == k || sum >= n) {
continue;
}
stack.add(i);
sum += i;
process(res, stack, i + 1, sum, k, n);
sum -= i;
stack.pop();
}
}
}
17.电话号码的字母组合
class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new LinkedList<>();
if (digits == null || ("").equals(digits)) {
return res;
}
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
StringBuilder stringBuilder = new StringBuilder();
process(res, digits, stringBuilder, numString, 0);
return res;
}
public void process(List<String> res, String digits, StringBuilder stringBuilder, String[] numString, int cur) {
if (cur == digits.length()) {
res.add(stringBuilder.toString());
return;
}
String str = numString[digits.charAt(cur) - '0'];
for (int i = 0; i < str.length(); i++) {
stringBuilder.append(str.charAt(i));
process(res, digits, stringBuilder, numString, cur + 1);
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
}
}