Problem:
Score: 400 points

Problem Statement

AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code.

The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code.

How many different PIN codes can he set this way?

Both the lucky number and the PIN code may begin with a 0.

Constraints

4 \leq N \leq 30000

S is a string of length N consisting of digits.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of different PIN codes Takahashi can set.

Sample Input 1

4
0224

Sample Output 1

3

Takahashi has the following options:

Erase the first digit of S and set 224.

Erase the second digit of S and set 024.

Erase the third digit of S and set 024.

Erase the fourth digit of S and set 022.

Thus, he can set three different PIN codes: 022, 024, and 224.

Sample Input 2

6
123123

Sample Output 2

17

Sample Input 3

19
3141592653589793238

Sample Output 3

329

Solution in Scala (2.11.7) (judge verdict: Accepted)

import java.io.{BufferedReader, InputStreamReader}

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val n = in.readLine().toInt
    val s = in.readLine()

    val cs = s.toCharArray.map(_.toInt - '0')

    val thirdChars = new Array[Set[Int]](n)
    val thirdCharsCount = new Array[Int](n)

    thirdChars(n - 1) = Set(cs(n - 1))
    thirdCharsCount(n - 1) = 1
    for {
      i <- (n - 2) to 2 by -1
    } {
      thirdChars(i) = thirdChars(i + 1) + cs(i)
      thirdCharsCount(i) = thirdChars(i).size
    }

    var count = 0
    val firstMemo = Array.ofDim[Boolean](10)
    val secondMemo = Array.ofDim[Boolean](n - 1, 10)

    for (
      i <- 0 until (n - 2)
      if !firstMemo(cs(i))
    ) {
      for (
        j <- i + 1 until (n - 1)
        if !secondMemo(i)(cs(j))
      ) {
        count += thirdCharsCount(j + 1)
        secondMemo(i)(cs(j)) = true
      }
      firstMemo(cs(i)) = true
    }

    System.out.println(
      count
    )
  }
}