給一個字符串,你可以選擇在一個字符或兩個相鄰字符之後拆分字符串,使字符串由僅一個字符或兩個字符組成,輸出所有可能的結果
樣例
樣例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);
}
}
}
};