Numbers At Most N Given Digit Set (H)
題目
Given an array of digits, 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 1:
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.
Example 2:
Input: digits = ["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 array.
Example 3:
Input: digits = ["7"], n = 8
Output: 1
Constraints:
1 <= digits.length <= 9digits[i].length == 1digits[i]is a digit from'1'to'9'.- All the values in
digitsare unique. 1 <= n <= 109
題意
用給定的數字組成一個正整數,使得它比目標值小,統計這樣的正整數的個數,
思路
記目標值的位數為len,如果組成的正整數k長度小于len,那么可以隨意組合;如果長度等于len,那么對第一位進行比較,如果k的第一位小于目標值的第一位,那么剩余位可以隨意組合,如果第一位相同,遞回求解即可,
代碼實作
Java
class Solution {
public int atMostNGivenDigitSet(String[] digits, int n) {
Arrays.sort(digits);
return helper(digits, n, false);
}
private int helper(String[] digits, int n, boolean fillAll) {
if (n == 0) {
return 0;
}
int count = 0;
String ns = n + "";
int len = ns.length();
int size = digits.length;
// 僅在第一次呼叫該方法時需要累加
if (!fillAll) {
for (int i = 1; i < len; i++) {
count += (int) Math.pow(size, i);
}
}
for (int i = 0; i < size; i++) {
if (digits[i].charAt(0) < ns.charAt(0)) {
count += (int) Math.pow(size, len - 1);
} else if (digits[i].charAt(0) == ns.charAt(0) && len == 1) {
count += 1;
break;
} else if (digits[i].charAt(0) == ns.charAt(0) && ns.charAt(1) != '0') {
count += helper(digits, Integer.parseInt(ns.substring(1)), true);
break;
}
}
return count;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/226067.html
標籤:其他
上一篇:云服務器(阿里云)的安全組設定
