iT邦幫忙

2025 iThome 鐵人賽

DAY 17
0
自我挑戰組

leetcode系列 第 17

leetcode 17. Letter Combinations of a Phone Number

  • 分享至 

  • xImage
  •  

題目:
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.
https://ithelp.ithome.com.tw/upload/images/20251001/20169340GyylFn4w8G.png
給定一個包含數字的字串,傳回該數字可能代表的所有字母組合。以任意順序2-9回傳答案。

下面給出了數字到字母的映射(就像電話按鈕一樣)。注意,1 不映射到任何字母。
https://ithelp.ithome.com.tw/upload/images/20251001/201693409VyFuNPSji.png
解題思路

這題屬於 回溯 (Backtracking) 的典型題:

建立數字與字母的映射表。

使用回溯遞迴 (DFS):

當目前組合的長度等於輸入字串長度 → 加入答案。

否則,取當前數字的所有字母,逐一加入組合並遞迴下一層。


上一篇
leetcode 16. 3Sum Closest
下一篇
leetcode 18. 4Sum
系列文
leetcode20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言