Last updated on July 20th, 2024 at 04:11 am
Here, We see Count Numbers with Unique Digits LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Backtracking, Dynamic Programming, Math
Companies
Level of Question
Medium
![Count Numbers with Unique Digits LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Count Numbers with Unique Digits LeetCode Solution
Table of Contents
Problem Statement
Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.
Example 1:
Input: n = 2
Output: 91
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99
Example 2:
Input: n = 0
Output: 1
1. Count Numbers with Unique Digits Leetcode Solution C++
class Solution { public: int countNumbersWithUniqueDigits(int n) { int sum = 1; if(n > 0) { int end = (n > 10)? 10 : n; for(int i = 0; i < end; i++) { sum += 9 * permutation(9, i); } } return sum; } int permutation(int n, int r) { if(r == 0) { return 1; }else{ return n * permutation(n - 1, r - 1); } } };
2. Count Numbers with Unique Digits Leetcode Solution Java
class Solution { public int countNumbersWithUniqueDigits(int n) { if (n > 10) { return countNumbersWithUniqueDigits(10); } int count = 1; // x == 0 long max = (long) Math.pow(10, n); boolean[] used = new boolean[10]; for (int i = 1; i < 10; i++) { used[i] = true; count += search(i, max, used); used[i] = false; } return count; } private int search(long prev, long max, boolean[] used) { int count = 0; if (prev < max) { count += 1; } else { return count; } for (int i = 0; i < 10; i++) { if (!used[i]) { used[i] = true; long cur = 10 * prev + i; count += search(cur, max, used); used[i] = false; } } return count; } }
3. Count Numbers with Unique Digits Solution JavaScript
var countNumbersWithUniqueDigits = function(n) { return [1,10,91,739,5275,32491,168571,712891,2345851][n] };
4. Count Numbers with Unique Digits Solution Python
class Solution(object): def countNumbersWithUniqueDigits(self, n): def count(k): if k == max(10 - n, 0): return 0 return k*(1 + count(k - 1)) if n == 0: return 1 return 9*count(9) + 10