Question: Using the built in REVERSE function on a nvarchar I expect '51.02' to be returned but instead receive 2.

```
DECLARE @HourMins nvarchar = '20.15'

SELECT REVERSE(@HourMins) digs

```

Can anyone tell me why?

[![enter image description here](https://i.stack.imgur.com/sAlpu.png)](https://i.stack.imgur.com/sAlpu.png)

Answer: 
The problem is that you miss combinations such as 2+6+2 (where a lesser number comes after a greater number), because you run (for example) `table[10] += table[10-2]` *before* `table[8] += table[8-6]`, so the former doesn't take into account the result of the latter.

To fix that, change this:

```
    for (i = 2; i <= n; i++)
        table[i] += table[i - 2];
    for (i = 3; i <= n; i++)
        table[i] += table[i - 3];
    for (i = 6; i <= n; i++)
        table[i] += table[i - 6];

```

to this:

```
    for (i = 1; i <= n; i++) {
        if (i >= 2) {
            table[i] += table[i - 2];
        }
        if (i >= 3) {
            table[i] += table[i - 3];
        }
        if (i >= 6) {
            table[i] += table[i - 6];
        }
    }

```

so that you handle e.g. `table[10]` only after you've fully processed e.g. `table[8]`.
You count the number of solutions, without taking into account the order of the elements.

For example, for `n = 5`, `2 + 3` count for one element only,`3 + 2`is considered as the same solution.

To get the result that you are looking for, you need two modifications:

1. Instead of counting the number of solutions, you have to memorize all the corresponding solutions. At this level, you don't need to take the order in consideration, just memorize the number of 2, 3, 6 corresponding to one solution. This allows you to keep the same program structure, basically the same efficient algorithm.
2. Then, for each particular solution `(x, y, z)`, where `x, y, z` are the multiplicities associated to 2, 3, 6, you have to evaluate the number of possibilities `N(x, y, z)` obtained by modifying the order of the elements.

The corresponding number of solutions is :

```
N(x, y, z) = C(s, x) * C(s-x, y) * C(s-x-z, z)

```

Where `s = x+y+z` and the `C(n, p)` are the binomial coefficients

Note that the last factor is equal to `C(z, z) = 1`.