解题思路:
(1)先排序,再使用递归搜索
class Solution {
private:
vector<vector<string>> v;
public:
vector<string> search(vector<string> &products,string &searchWord,int len) {
string str=searchWord.substr(0,len);
vector<string> s;
int count = 0;
for(int i=0;i<products.size();i++) {
if(products[i].substr(0,len)==str) {
count++;
if(count<=3) s.push_back(products[i]);
}
}
return s;
}
void helper(vector<string> &products,string &searchWord,int len) {
if(len>searchWord.length()) return;
vector<string> s = search(products,searchWord,len);
v.push_back(s);
helper(products,searchWord,len+1);
return;
}
vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
sort(products.begin(),products.end());
helper(products,searchWord,1);
return v;
}
};