class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
combine(n,k,1,0);
return result;
}
public void combine(int targetSum,int k,int startIndex,int sum){
if(sum > targetSum){
return;
}
if(path.size() == k){
if(sum == targetSum){
result.add(new ArrayList<>(path));
}
return;
}
for(int i = startIndex; i <= 9 - (k - path.size()) + 1 ;i++){
path.add(i);
sum +=i;
combine(targetSum,k,i+1,sum);
path.removeLast();
sum -= i;
}
}
}
电话号码的字母组合
class Solution {
List<String> result = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits == null || digits.length() == 0){
return result;
}
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
backTracing(digits,numString,0);
return result;
}
StringBuilder temp = new StringBuilder();
public void backTracing(String digits,String[] numString,int num){
if(num == digits.length()){
result.add(temp.toString());
return;
}
String str = numString[digits.charAt(num) - '0'];
for(int i= 0 ; i < str.length() ; i++){
temp.append(str.charAt(i));
backTracing(digits,numString,num + 1);
temp.deleteCharAt(temp.length()-1);
}
}
}