lucaswiman

Solution to http://11011110.livejournal.com/254164.html

Aug 9th, 2012
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.83 KB | None | 0 0
  1. require 'set'
  2. def _distinct_subsequences(s_prime, k_prime, cache)
  3.   if cache.key? [s_prime, k_prime]
  4.     return cache[[s_prime, k_prime]]
  5.   end
  6.   chars = s_prime.split('')
  7.   if k_prime > chars.length
  8.     return 0
  9.   elsif k_prime == chars.length
  10.     return 1
  11.   elsif k_prime == 1
  12.     result = chars.uniq.length
  13.   else
  14.     seen = Set.new
  15.     result = 0
  16.     chars.each_with_index do |c, i|
  17.       next if seen.include?(c)
  18.       seen << c
  19.       to_the_right = s_prime.slice(i+1..-1)
  20.       result += _distinct_subsequences(to_the_right, k_prime-1, cache)
  21.     end
  22.   end
  23.   cache[[s_prime, k_prime]] = result
  24.   return result
  25. end
  26.  
  27. def distinct_subsequences(s, k)
  28.   cache = {}
  29.   result = _distinct_subsequences(s, k, cache)
  30.   return result
  31. end
  32.  
  33. distinct_subsequences('food', 2) == 4
  34. distinct_subsequences('10'*100, 100) == 2**100
Add Comment
Please, Sign In to add comment