简体   繁体   中英

Why might a recursive solution have a much more complicated base case than a DP solution?

I'm working on an algorithm problem to find number of ways to decode an integer into a string of characters. I've worked out a DP solution and recursive solution.

The recursive solution seems to have a much more complicated base case. I'm trying to understand why that might be and if its a pattern or if I'm just really bad at writing recursive base cases.

DP solution:

# @param {String} s
# @return {Integer}
def num_decodings(s)
  return 0 if s.length == 0
  n = s.length
  memo = Array.new(n+1,0)
  memo[n] = 1
  memo[n-1] = s[n-1]=="0" ? 0 : 1
  (0...n-1).to_a.reverse.each do |i|
    next if s[i] == "0"
    memo[i] = s[i...(i+2)].to_i <= 26 ? memo[i+1] + memo[i+2] : memo[i+1]
  end
  puts memo.to_s
  return memo[0]
end

Recursive solution:

# @param {String} s
# @return {Integer}
def num_decodings(s)
    #puts "s: #{s}"
    return 0 if s.length == 0
    return 0 if s[0] == "0"
    return 1 if s.length == 1
    return 1 if s.length == 2 && s[1] == "0" && s.to_i <= 26
    return 0 if s.length == 2 && s[1] == "0" && s.to_i > 26
    return 2 if s.length == 2 && s.to_i <= 26
    return 1 if s.length == 2
    @ways ||= {}
    return @ways[s] if @ways[s]
    if s[0..1].to_i <= 26 
        @ways[s] = num_decodings(s[1..-1]) + num_decodings(s[2..-1])
    else
        @ways[s] = num_decodings(s[1..-1])
    end
    #puts @ways
    return @ways[s]
end

Input: "2545632102" Output: 2

It's this problem on Leetcode: https://leetcode.com/problems/decode-ways/

I continued working on the recursive solution and realized that while the DP solution only needs to account for n-1 and n-2, my recursive base case happens to be unnecessarily weird. So I simplified it and ended up with this:

def num_decodings(s)
    return 0 if s.length == 0
    return 0 if s[0] == "0"
    return 1 if s.length == 1
    @ways ||= {}
    return @ways[s] if @ways[s]
    if s[0..1].to_i <= 26
        prev = s.length <= 2 ? 1 : num_decodings(s[2..-1])
        @ways[s] = num_decodings(s[1..-1]) + prev
    else
        @ways[s] = num_decodings(s[1..-1])
    end
    return @ways[s]
end

This solution is already very similar to the DP solution and is at a similar degree of complexity.

Of course the DP solution is still faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM