Created
April 26, 2016 19:09
-
-
Save jianminchen/acbbf5fbd5fefa1a9fb2f7b3664bf4ed to your computer and use it in GitHub Desktop.
Leetcode17 Phone number DFS - a second practice using previous practice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace _17LetterCombinationOfAPhoneNUmber_DFS | |
{ | |
/* | |
* Leetcode 17: | |
* Given a digit string, return all possible letter combinations that | |
* the number could represent. | |
A mapping of digit to letters (just like on the telephone buttons) is given below. | |
* Input:Digit string "23" | |
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. | |
* | |
* Telephone dial pad: | |
* 0 1 2 3 4 5 6 7 8 9 | |
* String[] keyboard={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; | |
*/ | |
class Solution | |
{ | |
static void Main(string[] args) | |
{ | |
IList<string> list = letterCombination("23"); | |
// test result: "abc", "def", so 3x3 = 9 cases. | |
} | |
public static IList<string> letterCombination(string digits) | |
{ | |
IList<string> list = new List<string>(); | |
if (digits == null || digits.Length == 0) | |
return list; | |
string[] keyboard = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; | |
StringBuilder sb = new StringBuilder(); | |
buildResult(list, keyboard, digits, sb, 0); // think about design here | |
return list; | |
} | |
/* | |
* Julia's practice on April 26, 2016 | |
* Need to rewrite to get more experience. | |
* Static analysis: | |
* 1. use explanation variables c, s1, | |
* | |
*/ | |
private static void buildResult( | |
IList<string> list, | |
string[] keyboard, | |
string digits, // test case: "23" | |
StringBuilder sb, | |
int index) // test case: "23", index value 0 and 1 | |
{ | |
// need to do the backtracking, need to do the recursive solution | |
int len = digits.Length; | |
// index starting from 0 | |
if (index < len) // bug001 - not len -1, should be len | |
{ | |
char c = digits[index]; | |
string s1 = keyboard[c - '0']; | |
foreach (char nextChar in s1) | |
{ | |
string tmpS = sb.ToString(); | |
sb.Append(nextChar); | |
buildResult(list, keyboard, digits, sb, index + 1); | |
sb = new StringBuilder(tmpS); | |
} | |
} | |
else | |
{ | |
// add to the list | |
list.Add(sb.ToString()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment