Numbers At Most N Given Digit Set

Given an array of digits that is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13''551', and '1351315'.

Return the number of positive integers that can be generated that are less than or equal to a given integer n.

Example:

Input: digits = ["1","3","5","7"], n = 100
Output: 20
Explanation: 
The 20 numbers that can be written are:
1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int atMostNGivenDigitSet(vector<string&digitsint n)
{
    string num = to_string(n);
    int K = num.length();
    vector<intdp(K + 1);
    dp[K] = 1;
    for (int i = K - 1i >= 0i--)
    {
        for (string d : digits)
        {
            if (d[0] < num[i])
                dp[i] += pow(digits.size(), K - i - 1);
            else if (d[0] == num[i])
                dp[i] += dp[i + 1];
        }
    }
    for (int i = 1i < Ki++)
        dp[0] += pow(digits.size(), i);
    return dp[0];
}

int main()
{
    vector<stringdigits = {"1""3""5""7"};
    int n = 100;

    cout << atMostNGivenDigitSet(digits,n);

    return 0;
}


No comments:

Post a Comment