LeetCode(17) - Letter Combinations of a Phone Number


  經典的backtracking(回溯算法)的題目。當一個題目,存在各種滿足條件的組合,並且需要把它們全部列出來時,就可以考慮backtracking了。當然,backtracking在一定程度上屬於窮舉,所以當數據特別大的時候,不合適。而對於那些題目,可能就需要通過動態規划來完成。

  這道題的思路很簡單,假設輸入的是"23",2對應的是"abc",3對應的是"edf",那么我們在遞歸時,先確定2對應的其中一個字母(假設是a),然后進入下一層,窮舉3對應的所有字母,並組合起來("ae","ad","af"),當"edf"窮舉完后,返回上一層,更新字母b,再重新進入下一層。這個就是backtracing的基本思想。

  代碼如下:

 1 public class Solution {
 2     public List<String> letterCombinations(String digits) {
 3         //把table上的數字對應的字母列出來,當輸入為2是,digits[2]就是2所對應的"abc"
 4         String[] table = new String[] 
 5                              {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
 6         List<String> list = new ArrayList<String>();
 7         //index從0開始,即digits的第一個數字
 8         letterCombinations(list,digits,"",0,table);
 9         return list;
10     }
11     
12     private void letterCombinations (List<String> list, String digits, 
13                                     String curr, int index,String[] table) {
14         //最后一層退出條件
15         if (index == digits.length()) {
16             if(curr.length() != 0) list.add(curr);
17             return;
18         }
19         
20         //找到數字對應的字符串
21         String temp = table[digits.charAt(index) - '0'];
22         for (int i = 0; i < temp.length(); i++) {
23             //每次循環把不同字符串加到當前curr之后
24             String next = curr + temp.charAt(i);
25             //進入下一層
26             letterCombinations(list,digits,next,index+1,table);
27         }
28     }
29 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM