Problem:
Score : 500 points

Problem Statement

Find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten.

Constraints

1 \leq N < 10^{100}

1 \leq K \leq 3

Input

Input is given from Standard Input in the following format:

N
K

Output

Print the count.

Sample Input 1

100
1

Sample Output 1

19

The following 19 integers satisfy the condition:

1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100

Sample Input 2

25
2

Sample Output 2

14

The following 14 integers satisfy the condition:

11,12,13,14,15,16,17,18,19,21,22,23,24,25

Sample Input 3

314159
2

Sample Output 3

937

Sample Input 4

9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
3

Sample Output 4

117879300

Solution in Ruby (2.3.3) (judge verdict: Wrong Answer)

class Integer
  def combination(k)
    return 1 if k.zero?

    (self - k + 1..self).inject(:*) / k.factorial
  end

  def permutation(k)
    return 1 if k.zero?

    (self - k + 1..self).inject(:*)
  end

  def factorial
    return 1 if self.zero?

    (1..self).inject(:*)
  end
end


n = gets.chop
n_len = n.length
k = gets.to_i
count = 0
count_k1 = (n_len-1).combination(k-1) * (9 ** (k-1))

# 下位の桁から順位１桁ずつあげて、その桁で可能な数をかぞえあげる
# ただし、一番大きい桁ではkの数とk-1の数を数え上げておく
(1..(n_len-1)).each do |digit|
  next if k > digit
  count += (digit-1).combination(k-1) * (9 ** k)
end

# nの桁に達したら、(n-1)*(n-1桁まででのk-1実現数)
count += (n[0].to_i-1) * count_k1

# ただし、nが区切りに良い数字かつnそのものがkの条件を満たす場合、カウントされなくなってしまうので、nが区切りが良い数字の場合はcount+=1
if n[1..-1] == '0' * (n_len-1)
  puts count+1
  exit 0
end

# 今度は上位の桁から順位１桁ずつ下げていく。ここは多分再帰が必要。kとdigitを受け取って、k=0なら実現数１、k!=0なら自身がぜろパターンと自身がぜろ以外パターンで分岐
def n_pat(k, num_s)
  return 0 if k.zero?
  return 1 if num_s.length.zero?
  return 0 if k < num_s.length

  num_s[0].to_i * (n_pat(k, num_s[1..-1]) + n_pat(k-1, num_s[1..-1]))
end

n = n[1..-1]
while n[0] == '0'
  n = n[1..-1]
end

puts count + n_pat(k-1, n)