给一个字符串,你可以选择在一个字符或两个相邻字符之后拆分字符串,使字符串由仅一个字符或两个字符组成,输出所有可能的结果
样例
样例1
输入: "123"
输出: [["1","2","3"],["12","3"],["1","23"]]
样例2
输入: "12345"
输出: [["1","23","45"],["12","3","45"],["12","34","5"],["1","2","3","45"],["1","2","34","5"],["1","23","4","5"],["12","3","4","5"],["1","2","3","4","5"]]
思路:简单的深度搜索,每一个字符要么自成一个字符串进行递归,要么就和下一个字符组成字符串进行递归即可
class Solution {
public:
/*
* @param : a string to be split
* @return: all possible split string array
*/
vector<vector<string>> splitString(string& s) {
// write your code here
vector<vector<string>> res;
dfs(s,res,vector<string>(),0);
return res;
}
void dfs(string& s, vector<vector<string>> &res,vector<string> tmp,int index)
{
if(index>=s.size()){
res.push_back(tmp);return;
}
else
{
string t="";
t+=s[index];
tmp.push_back(t);
dfs(s,res,tmp,index+1);
tmp.pop_back();
if(index+1<s.size())
{
t+=s[index+1];
tmp.push_back(t);
dfs(s,res,tmp,index+2);
}
}
}
};