代码随想录day25|216. 组合总和 III、17.电话号码的字母组合

216. 组合总和 III

private List> ans = new ArrayList<>();
private LinkedList path = new LinkedList<>();
private int k;
public List> combinationSum3(int k, int n) {
    this.k = k;
    dfs(9, n);
    return ans;
}
void dfs(int i, int t){
    int d = k - path.size();
    if(i < d){
        return;
    }
    if(t < 0 || t > (2* i - d + 1)* d /2){
        return;
    }
    if(k == path.size()){
        ans.add(new ArrayList<>(path));
        return;
    }
    //不选i
    dfs(i - 1, t);
    //选i
    path.add(i);
    dfs(i - 1, t - i);
    path.pollLast();
}

17.电话号码的字母组合

private char[] digits, path;
private final List ans = new ArrayList<>();
private static final String[] letterMap = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List letterCombinations(String digits) {
    int len = digits.length();
    if(len == 0){
        return List.of();
    }
    this.digits = digits.toCharArray();
    path = new char[len];
    dfs(0);
    return ans;
}
private void dfs(int i){
    if(i == digits.length){
        ans.add(new String(path));
        return;
    }
    for(char c: letterMap[digits[i] - '0'].toCharArray()){
        path[i] = c;
        dfs(i + 1);
    }
}

你可能感兴趣的:(代码随想录二刷笔记,数据结构,算法)