其实是跳台阶问题,给想复杂了。。
func translateNum(num int) int {
mp1 := make(map[string]string)
for i := 0; i < 26; i++ {
ss := string('a'+i)
nn := strconv.Itoa(i)
mp1[nn]=ss
}
mp2 := make(map[string]int)
s := strconv.Itoa(num)
n := len(s)
var dfs func(idx int, str string)
dfs = func(idx int, str string) {
if idx == n {
mp2[str] = 1
return
}
for i := idx+1; i <= n; i++ {
nn := s[idx:i]
ss, ok := mp1[nn]
if !ok {
break
}
dfs(i, str+ss)
}
}
dfs(0, "")
return len(mp2)
}
优化
func translateNum(num int) int {
s := strconv.Itoa(num)
n := len(s)
if n <= 1 {
return n
}
dp := make([]int, n)
dp[0] = 1
dp[1] = 1
if s[:2] <= "25" && s[:2] >= "10" {
dp[1] = 2
}
for i := 2; i < n; i ++ {
dp[i] = dp[i-1]
ss := s[i-1:i+1]
if ss <= "25" && ss >= "10" {
dp[i] += dp[i-2]
}
}
return dp[n-1]
}