LeetCode--357--medium--CountNumbersWithUniqueDigits

package com.app.main.LeetCode.dynamic;

/**
 * 357
 *
 * medium
 *
 * https://leetcode.com/problems/count-numbers-with-unique-digits/
 *
 * Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
 *
 * Example:
 *
 * Input: 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
 *
 * Created with IDEA
 * author:Dingsheng Huang
 * Date:2020/1/13
 * Time:下午8:25
 */
public class CountNumbersWithUniqueDigits {

    public int countNumbersWithUniqueDigits(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return 10;
        }
        int[] dp = new int[n + 1];
        dp[0] = 0;
        dp[1] = 10;
        dp[2] = 91;
        int pre = 8;
        for (int i = 3; i <= n; i++) {
            if (pre == 0) {
                return dp[i];
            }
            dp[i] = dp[i - 1] + (dp[i - 1] - dp[i - 2]) * pre;
            pre--;
        }
        return dp[n];
    }
}
发布了187 篇原创文章 · 获赞 26 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/huangdingsheng/article/details/103978141