<br> We have a sorted set of digits `D`, a non-empty subset of `{'1','2','3','4','5','6','7','8','9'}`. (Note that `'0'` is not included.)html
Now, we write numbers using these digits, using each digit as many times as we want. For example, if D = {'1','3','5'}
, we may write numbers such as '13', '551', '1351315'
.git
Return the number of positive integers that can be written (using the digits of D
) that are less than or equal to N
.github
Example 1:数组
Input: D = ["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.
Example 2:less
Input: D = ["1","4","9"], N = 1000000000 Output: 29523 Explanation: We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits of D.
Note:this
D
is a subset of digits '1'-'9'
in sorted order.1 <= N <= 10^9
<br> 这道题给了咱们一个有序字符串数组,里面是0到9之间的数(这里博主就纳闷了,既然只有一位数字,为啥不用 char 型,而要用 string 型),而后又给了一个整型数字N,问无限制次数使用D中的任意个数字,能组成多个不一样的小于等于D的数字。先来分析例子1,当N为 100 时,全部的一位数和两位数都是能够的,既然能够重复使用数字,假设总共有n个数字,那么对于两位数来讲,十位上和个位上分别都有n种可能,总共就是 n^2 种可能,对于一位数来讲,总共n种可能。那么看到这里就能够概括出当N总共有 len 位的话,咱们就能够快速的求出不超过 len-1 位的全部状况综合,用个 for 循环,累加n的指数便可。而后就要来分析和数字N位数相等的组合,题目中的两个的例子的N都是1开始的,实际上N能够是任何数字,举个例子来讲吧,假如 D={"1","3","5","7"},N=365,那么根据前面的分析,咱们能够很快的算出全部的两位数和一位数的组合状况总数 4 + 4^2 = 20 个。如今要来分析三位数都有哪些组合,因为D数组是有序的,因此咱们从开头遍历的话先取到的就是最小的,这时候有三种状况,小于,等于,和大于,每种的处理状况都有些许不一样,这里就拿上面提到的例子进行一步一步的分析:code
代码以下:htm
<br>blog
class Solution { public: int atMostNGivenDigitSet(vector<string>& D, int N) { string str = to_string(N); int res = 0, n = D.size(), len = str.size(); for (int i = 1; i < len; ++i) res += pow(n, i); for (int i = 0; i < len; ++i) { bool hasSameNum = false; for (string &d : D) { if (d[0] < str[i]) res += pow(n, len - 1 - i); else if (d[0] == str[i]) hasSameNum = true; } if (!hasSameNum) return res; } return res + 1; } };
<br> Github 同步地址:three
https://github.com/grandyang/leetcode/issues/902
<br> 参考资料:
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/225123/c%2B%2B100
<br> [LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)