算法练习第二十五天| 216.组合总和III、17.电话号码的字母组合
leetcode题目链接
17
216
216.组合总和III
class Solution {
List<Integer> path = new ArrayList();
List<List<Integer>> result = new ArrayList();
public List<List<Integer>> combinationSum3(int k, int n) {
backTrace(k,n,1,0);
return result;
}
public void backTrace(int k,int n,int startIndex,int sum){
//结束条件
if(path.size() == k){
if(sum == n) result.add(new ArrayList(path));
return;
}
for(int i = startIndex;i<=9-(k-path.size())+1;i++){
sum += i;
path.add(i);
if (sum > n) { // 剪枝操作
sum -= i; // 剪枝之前先把回溯做了
path.removeLast(); // 剪枝之前先把回溯做了
return;
}
backTrace(k,n,i+1,sum);
sum -=i;
path.removeLast();
}
}
}
17.电话号码的字母组合
class Solution {
List<String> result = new ArrayList();
static Map<Integer,String> map = new HashMap();
StringBuilder tmp = new StringBuilder();
static {
map.put(2,"abc");
map.put(3,"def");
map.put(4,"ghi");
map.put(5,"jkl");
map.put(6,"mno");
map.put(7,"pqrs");
map.put(8,"tuv");
map.put(9,"wxyz");
}
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return result;
}
backTrace(digits,0);
return result;
}
/**
params:index遍历到第几个数字
*/
public void backTrace(String digits,int index){
//终止条件
//这里为什么不是index==digits.length()-1???
//需要理解遍历到这个最后的字符,和遍历完最后这个字符的区别
if(index == digits.length()){
result.add(tmp.toString());
return;
}
int digit = digits.charAt(index) - '0';
String s= map.get(digit);
for(int i = 0;i<s.length();i++){
tmp.append(s.charAt(i));
backTrace(digits,index+1);
tmp.deleteCharAt(tmp.length()-1);
}
}
}