【JAVA、C++】LeetCode 017 Letter Combinations of a Phone Number

时间:2023-03-08 21:58:00

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.

解题思路:

思路一:

使用DFS算法,JAVA实现如下:

	    static String[] alpha = new String[] {
" ","1", "abc", "def","ghi", "jkl", "mno","pqrs", "tuv", "wxyz"
};
static StringBuilder sb = new StringBuilder();
static void dfs(List<String> list, String digits, int cur) {
if (cur >= digits.length())
list.add(sb.toString());
else {
for (int i = 0; i < alpha[digits.charAt(cur) - '0'].length(); i++) {
sb.append(alpha[digits.charAt(cur) - '0'].charAt(i));
dfs(list, digits, cur + 1);
sb.deleteCharAt(sb.length() - 1);
}
}
}
static public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<String>();
if (digits.length()==0)
  return list;
dfs(list, digits, 0);
return list;
}

C++:

 class Solution {
public:
const string alpha[] = {" ","", "abc", "def","ghi", "jkl", "mno","pqrs", "tuv", "wxyz"};
void dfs(vector<string> &list, string &digits, int cur,string sb) {
if (cur >= digits.length())
list.push_back(sb);
else {
for (char a : alpha[digits[cur] - '']) {
sb.push_back(a);
dfs(list, digits, cur + ,sb);
sb.pop_back();
}
}
}
vector<string> letterCombinations(string digits) {
vector<string> list;
if (digits.length() == )
return list;
dfs(list, digits, ,"");
return list;
}
};

思路二:

凡是用到递归的地方都能用循环解决,因此可以用循环算法,JAVA实现如下:

static public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<String>();
String[] alpha = new String[] {
" ","1", "abc", "def","ghi", "jkl", "mno","pqrs", "tuv", "wxyz"
};
if (digits.length()==0)
return list;
int[] number = new int[digits.length()];//存储每次遍历字符位置
int index = 0;
while(index>=0) {
StringBuilder sb = new StringBuilder();
for(int i=0; i<digits.length(); i++)
sb.append(alpha[digits.charAt(i)-'0'].charAt(number[i]));
list.add(sb.toString());
// 每回合需要重置index到末尾
index = digits.length()-1;
while(index>=0) {
if( number[index] < (alpha[digits.charAt(index)-'0'].length()-1) ) {
number[index]++;
break;
} else {
number[index] = 0;
index--;
}
}
}
return list;
}