> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/dynamic-programming/n-digit-numbers-with-digit-sum-s.md).

# N digit numbers with digit sum S

Find out the number of `N` digit numbers, whose digits on being added equals to a given number `S`. Note that a valid number starts from digits `1-9` except the number `0` itself. i.e. leading zeroes are not allowed.

Since the answer can be large, output answer modulo `1000000007`

`N = 2, S = 4`

\
Valid numbers are `{22, 31, 13, 40}`\
Hence output `4`.

```java
public class Solution {

    private long MOD = 1000000007L;

    public int solve(int n, int sum) {
        long[][] dp = new long[n + 1][sum + 1];
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= sum; j++) {
                dp[i][j] = -1;
            }
        }
        long count = 0;
        // For first digit we can only take 1->9
        for (int i = 1; i <= 9; i++) {
            if (sum - i >= 0) {
                count += recursion(n - 1, sum - i, dp) % MOD;
            }
        }
        return (int) (count % MOD);
    }

    private long recursion(int n, int sum, long[][] dp) {
        if (n == 0) {
            return sum == 0 ? 1 : 0;
        }
        if (dp[n][sum] != -1)
            return dp[n][sum];
        long count = 0;
        for (int i = 0; i <= 9; i++) {
            if (sum - i >= 0) {
                count += recursion(n - 1, sum - i, dp);
            }
        }
        dp[n][sum] = count % MOD;
        return dp[n][sum];
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mayanktyagi3111.gitbook.io/interview-prep/dynamic-programming/n-digit-numbers-with-digit-sum-s.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
