Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Sure it can be done in polynomial time. It's an excellent exercise in <a href="http://en.wikipedia.org/wiki/Dynamic_programming" rel="noreferrer">dynamic programming</a> or <a href="http://en.wikipedia.org/wiki/Memoization" rel="noreferrer">memoization</a>.</p> <p>Lets assume N (the number of digits) equals 10 for the example.</p> <p>Think of it recursively like this: <em>How many numbers can I construct using 10 digits starting from <code>1</code>?</em></p> <p>Answer is</p> <pre><code>[number of 9-digit numbers starting from 8] + [number of 9-digit numbers starting from 6]. </code></pre> <p>So <em>how many "9-digit numbers starting from 8" are there?</em> Well,</p> <pre><code>[number of 8-digit numbers starting from 1] + [number of 8-digit numbers starting from 3] </code></pre> <p>and so on. Base case is reached when you get the question <em>"How many 1-digit numbers are there starting from <code>X</code>"</em> (and the answer is obviously 1).</p> <p>When it comes to complexity, the key observation is that you reuse previously computed solutions. That is for instance, the answer to <em>"how many 5-digit numbers starting from <code>3</code>"</em> there are, can be used both when answering <em>"how many 6-digit numbers are there starting from <code>8</code>"</em> AND <em>"how many 6-digit numbers are there starting from <code>4</code>"</em>. This reuse make the complexity collapse from exponential to polynomial.</p> <p>Let's take a closer look at the complexity of a dynamic programming solution:</p> <p>Such implementation would fill in a matrix in the following way:</p> <pre><code>num[1][i] = 1, for all 0&lt;=i&lt;=9 -- there are one 1-digit number starting from X. for digits = 2...N for from = 0...9 num[digits][from] = num[digits-1][successor 1 of from] + num[digits-1][successor 2 of from] + ... num[digits-1][successor K of from] return num[N][1] -- number of N-digit numbers starting from 1. </code></pre> <p>The algorithm simply fills the matrix one cell at a time, and the matrix is of dimension 10*N, and thus runs in <strong>linear time</strong>.</p> <hr> <p>Wrote it down from the top of my head, please correct me if there are any typos.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload