程式碼隨想錄演算法訓練營第第25天 | 216.組合總和III 、17.電話號碼的字母組合

YuanYF6發表於2024-06-02

今天的題比較簡單,重點是在於剪枝

216.組合總和III

如果把 組合問題理解了,本題就容易一些了。
題目連結/文章講解:https://programmercarl.com/0216.組合總和III.html
影片講解:https://www.bilibili.com/video/BV1wg411873x

/**
 * @param {number} k
 * @param {number} n
 * @return {number[][]}
 */
var combinationSum3 = function(k, n) {
    const res = [];
    const path = [];
    let count = 0;
    let cycles = n < 9 ? n : 9;
    const backtracking = (startIndex) => {
        if (path.length === k) {
            if (count === n) {
                res.push([...path]);
            }
            return;
        }
        for (let i=startIndex;i<=cycles - (k-path.length)+1;i++) {
            path.push(i);
            count += i;
            if (count > n) {
                path.pop();
                count-=i;
                return;
            }
            backtracking(i+1);
            path.pop();
            count -= i;
        }
    }
    backtracking(1);
    return res;
};

17.電話號碼的字母組合

本題大家剛開始做會有點難度,先自己思考20min,沒思路就直接看題解。
題目連結/文章講解:https://programmercarl.com/0017.電話號碼的字母組合.html
影片講解:https://www.bilibili.com/video/BV1yV4y1V7Ug

/**
 * @param {string} digits
 * @return {string[]}
 */
var letterCombinations = function(digits) {
    if (digits.length === 0) {
        return [];
    }
    const mapping = [[],[],['a','b','c'],['d','e','f'],['g','h','i'], ['j','k','l'],['m','n','o'],['p','q','r','s'],['t','u','v'],['w','x','y','z']];
    let len = digits.length;
    let res = [];
    let path = [];
    const backtracking = (startIndex) =>{
        if(path.length === len) {
            res.push(path.join(''));
            return;
        }

            let arr = mapping[digits[startIndex]];
            for (let j =0;j<arr.length;j++) {
                path.push(arr[j]);
                backtracking(startIndex+1);
                path.pop();
            }
    }
    backtracking(0);
    return res;
};

相關文章