1.组合数
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backtracking(n,k,1,0); //和为0,i从1开始遍历
return result;
}
public void backtracking(int n, int k, int startIndex, int sum){
if(sum>n){
return;
}
if(path.size() == k){ //选到了k个数
if(n==sum){ //值为sum,加入到答案列表中
result.add(new ArrayList<>(path));
}
return;
}
for(int i = startIndex; i<=9-(k - path.size())+1; i++){ //
path.add(i);
sum += i;
backtracking(n,k,i+1,sum);
path.removeLast();
sum-=i;
}
}
}
2.
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();
public void backTracking(String digits, String[] numString, int n){
if(n == digits.length()){ //遍历完digits中的数字
list.add(temp.toString());
return;
}
String str = numString[digits.charAt(n) - '0']; //得到数字对应的字符串
for (int i = 0; i < str.length(); i++) {
temp.append(str.charAt(i));
backTracking(digits, numString, n + 1);
//回溯
temp.deleteCharAt(temp.length() - 1);
}
}
}