![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/763b8e2b3512932cdefca7c5a0cc5a94.png)
c++ dfs
class Solution {
public:
typedef unsigned long long LL;
LL charToInt(string s){
int len = s.length();
LL res = 0;
for(LL i = 0; i < len; i++){
res = res * 10;
res += s[i]-'0';
}
return res;
}
bool isok = false;
//str[1位--->s.length()位]
void dfs(int i,int n,string s,LL parentVal){
//str[1-n]
string str = s.substr(i,n);
LL val = charToInt(str);
//结束条件
if(isok) return;
if(val+1 != parentVal) return;
if(i+n >= s.length()){
if(val+1 == parentVal) isok = true;
return;
}
//搜索下一个
int maxAddNum = s.length()-(i+n);
for(int k = 1; k <= maxAddNum; k++){
//起始下标为i+n,
dfs(i+n,k,s,val);
}
}
bool splitString(string s) {
int len = s.length();
isok = false;
//第一个字符串,位置可能为[0,len-1位] ,第二个字符串至少是[len]
for(int i = 1; i <= len-1; i++){ //s有 len位, 第一个字符串最多len-1位
LL val = charToInt(s.substr(0,i)); //s[0,多少位]
//parentVal设为val+1
dfs(0,i,s,val+1);
if(isok) return true;
}
return false;
}
};
java DFS
C++ sustr(index,number)
java substring(startIndex,endIndex)
class Solution {
boolean isok = false;
long strTolong(String s){
int len = s.length();
long sum = 0;
for(int i = 0; i < len; i++){
sum *= 10;
sum += s.charAt(i)-'0';
}
return sum;
}
void dfs(int i,int j,String s,long parentValue){
//实际上是[i,j)
long nowValue = strTolong(s.substring(i, j));
if(nowValue+1 != parentValue) return;
if(j == s.length()){
if(nowValue+1 == parentValue) isok = true;
return;
}
for(int k = j+1; k <= s.length(); k++) dfs(j,k,s,nowValue);
}
public boolean splitString(String s) {
int len = s.length();
isok = false;
//endIndex 最多取到, len-1, 那么实际的第一个字符串最多取到, [0,len-2](下标表示)
for(int i = 1; i <= len-1; i++){
long parentValue = strTolong(s.substring(0, i));
dfs(0,i,s,parentValue+1);
if(isok) return true;
}
return false;
}
}