您提出的问题与Leetcode Challenge 非常相似。这个想法是使用Backtracking
伪伪代码:
result := string Array
CartesianProduct(rowIndex, ArrayList, stringSoFar):
if rowIndex equal ArrayList.size:
Add stringSoFar to result
return
for(eachItem in ArrayList[rowIndex])
CartesianProduct(rowIndex +1 , ArrayList, stringSoFar + eachItem)
return
这是一个执行所有计算的主力,可以像CartesianProduct(0, list of Array to be multiplied, "")一样调用
假设您的ArrayList = [['A'], ['C', 'D']]。和CP 是CartesianProduct
CP(0, AL, "")
(Take 'A')/
/
CP(1, AL, "A") (stringSoFar becomes 'A')
(Take C) / \(Take 'D'.Second Iteration with second array['C', 'D'])
/ \
CP(2, AL, "AC") CP(2, AL, "AD")
/ \
rowIndex equal size. rowIndex equals listSize i.e No more list to look
Add "AC" and return Add stringsoFar ("AD") to result and rerturn
我对 Leetcode 问题的解决方案(但在 C++ 中)。希望它能给你一些用 PHP 编写的想法
class Solution {
public:
map<char, vector<string>> values {
{'2', vector<string>{"a", "b", "c"}},
{'3', vector<string>{"d", "e", "f"}},
{'4', vector<string>{"g", "h", "i"}},
{'5', vector<string>{"j", "k", "l"}},
{'6', vector<string>{"m", "n", "o"}},
{'7', vector<string>{"p", "q", "r", "s"}},
{'8', vector<string>{"t", "u", "v"}},
{'9', vector<string>{"w", "x", "y", "z"}}
};
vector<string> answer;
void doComb(int index, string digits, string sofar)
{
if(index == digits.size())
{
if(sofar != "")
{
answer.push_back(sofar);
}
return;
}
for(auto lett : values[digits[index]])
{
doComb(index + 1, digits, sofar + lett);
}
return;
}
vector<string> letterCombinations(string digits) {
doComb(0, digits, "");
return answer;
}
};