LeetCode刷题 Day25

104 阅读2分钟

LeetCode刷题 Day25

216. Combination Sum III

Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

  • Only numbers 1 through 9 are used.
  • Each number is used at most once.

Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]
Explanation:
1 + 2 + 4 = 7
There are no other valid combinations.

Example 2:

Input: k = 3, n = 9
Output: [[1,2,6],[1,3,5],[2,3,4]]
Explanation:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.

Example 3:

Input: k = 4, n = 1
Output: []
Explanation: There are no valid combinations.
Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.

思路:

  • 和77题类似,但是加了一个加法的限制条件 这样临界条件就变成了 (path.length === k && sum === n)

代码:

var combinationSum3 = function(k, n) {
    let res = [];

    var helper = function(path, level, sum) {
        if (path.length === k && sum === n) {
            res.push([...path]);
            return res;
        }

        for (let i = level; i <= 9; i++) {
            path.push(i);
            helper(path, i + 1, sum + i);
            path.pop();
        }
    }

    helper([], 1, 0);
    return res;
};

17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example 1:

Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:

Input: digits = ""
Output: []

Example 3:

Input: digits = "2"
Output: ["a","b","c"]

思路:

  • 依然要弄清楚level和for的组合,这个和组合问题是有些不同的。组合问题为了去重在for loop中使用了 startIndex, 而这个问题不需要,直接到下一层取从0开始的值。 image.png

代码:

var letterCombinations = function(digits) {
    let  digitsMap = {
        "2": "abc",
        "3": "def",
        "4": "ghi",
        "5": "jkl",
        "6": "mno",
        "7": "pqrs",
        "8": "tuv",
        "9": "wxyz"
    };
    const res = [];
    if (!digits) return res;
    let helper = function(path, level) {
        if (path.length === digits.length) {
            res.push(path);
            return;
        }

        const num = digits[level];
        const str = digitsMap[num];
        for (let i = 0; i < str.length; i++) {
            helper(path + str[i], level + 1);
        }
    }

    helper([], 0);
    return res;
};