[Leetcode] 17. Letter Combinations of a Phone Number

Seongjun Lee·2022년 2월 19일
0

[Leetcode] - Problem

목록 보기
17/43
post-thumbnail

Problem

문제 링크

주어진 숫자 다이얼을 이용하여 아래 키패드로 나올수 있는 문자 조합을 모두 구하여하려.

핸드폰 자판

Solution

  1. 번호마다 키 배열을 매핑해둔다.
  2. 재귀함수를 이용해서 순차적으로 올수있는 경우에대해 최대 길이에서 값을 저장해둔다.

JS CODE

/**
 * @param {string} digits
 * @return {string[]}
 */
var letterCombinations = function (digits) {
  const phoneKeypad = {
    2: ['a', 'b', 'c'],
    3: ['d', 'e', 'f'],
    4: ['g', 'h', 'i'],
    5: ['j', 'k', 'l'],
    6: ['m', 'n', 'o'],
    7: ['p', 'q', 'r', 's'],
    8: ['t', 'u', 'v'],
    9: ['w', 'x', 'y', 'z'],
  }

  let answer = []

  const combinationStr = (digits, deep, strs) => {
    if (deep === digits.length) {
      strs.join() && answer.push(strs.join(''))
      return
    }

    for (const d of phoneKeypad[digits[deep]]) {
      strs[deep] = d
      combinationStr(digits, deep + 1, strs)
    }
  }

  combinationStr(digits, 0, Array(digits.length))

  return answer
}
profile
Hi there 👋

0개의 댓글