代码随想录Day24打卡 回溯算法(1)

33 阅读1分钟

77 组合

回溯算法应该在for loop中push/pop

var combine = function(n, k) {
    const res = [], path = []
    const dfs = (start) => {
        if (path.length === k) {
            res.push([...path])
            return 
        }
        for (let num = start + 1; num <= n; num += 1) {
            path.push(num)
            dfs(num)
            path.pop()
        }
    }
    dfs(0)
    return res
};

216 组合总数(3)

var combinationSum3 = function(k, n) {
    const res = [], path = []
    const dfs = (start, sum) => {
        if (path.length > k) {
            return
        }
        if (sum > n) {
            return 
        }
        if (sum === n) {
            if (path.length === k) {
                res.push([...path])
            } else {
                return 
            }
        }
        for (let i = start; i <= 9; i++) {
            path.push(i)
            dfs(i + 1, sum + i)
            path.pop()
        }
    }
    dfs(1, 0)
    return res
};

17 电话号码的字母组合

var letterCombinations = function (digits) {
    const mapping = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]

    let path = ""
    const res = []

    const dfs = (start) => {
        if (digits.length === path.length) {
            res.push(path)
            return
        }

        const digit = digits.charCodeAt(start) - '0'.charCodeAt(0);
        for (let c of mapping[digit].split("")) {
            path += c
            dfs(start + 1)
            path = path.slice(0, path.length - 1)
        }

    }

    if (digits.length === 0) return res
    dfs(0)
    return res;
};