用c ++分割数字

时间:2014-01-26 15:14:04

标签: c++ function split numbers

我必须制作一个执行以下操作的程序:输入应为n(n> 1)。如果n = 5,则应发生以下情况:

1 1 1 1 1
1 1 1 2 
1 1 2
1 1 3
1 4
2 3

正如你所看到的,没有两条相同的行,顺序是严格的 - 从最低数字到最高数字。

我有一个代码,在同样的情况下输出:

1 1 1 1 1
2 1 1 1
2 2 1
3 1 1
3 2
4 1

正如您所看到的,订单是逆转的,这是无意的。我该如何解决这个问题?

以下是代码:

#include <iostream>
#include <stdio.h>
using namespace std;

unsigned *mp;

void print(unsigned length)
{
    unsigned i;
    for (i = 1; i < length; i++) printf("%u ", mp[i]);
    printf("%u\n", mp[length]);
}

void devNum(unsigned n, unsigned pos)
{
    unsigned k;
    for (k = 1; k <= n; k++)
    {
        if (n != k)
        {
            mp[pos] = k;
            if (mp[pos] <= mp[pos - 1])
            {
                devNum(n - k, pos + 1);
            }
        }
        else
        {
            mp[pos] = k;
            if (pos > 1 && mp[pos] <= mp[pos - 1]) print(pos);
        }
    }
}

int main(void)
{
    unsigned n;
    cin >> n;
    mp = new unsigned[n + 1];
    mp[0] = n + 1;
    devNum(n, 1);
    delete[] mp;
    return 0;
}

1 个答案:

答案 0 :(得分:0)

编辑:我重新编写了devNum()main()以符合新规范。请注意,我更改了mp[0]中填写的值。

void devNum(unsigned n, unsigned pos)
{
    for (mp[pos] = mp[pos-1]; mp[pos] <= n; ++mp[pos])
    {
        if(mp[pos] != n)
        {
            devNum(n - mp[pos], pos + 1);
        }
        else
        {
            if (pos > 1) print(pos);
        }
    }
}

int main(void)
{
    unsigned n;
    cin >> n;
    mp = new unsigned[n+1];
    mp[0] = 1;
    devNum(n, 1);
    delete [] mp;
    return 0;
}

(旧版规范)

更改

void devNum(unsigned n, unsigned pos)
{
    unsigned k;
    for (k = n; k >= 1; k--)
    /* ... */

void devNum(unsigned n, unsigned pos)
{
    unsigned k;
    for (k = 1; k <= n; k++)
    {
        if (n != k)
        {
            mp[pos] = k;
            if (mp[pos] <= mp[pos - 1])
            {
                devNum(n - k, pos + 1);
            }
        }
        else
        {
            mp[pos] = k;
            if (pos > 1 && mp[pos] <= mp[pos - 1]) print(pos);
        }
    }
}

请注意,在致电pos > 1之前,我会检查print()以避免单5

要删除固定的MAX限制,您可以在mp中动态分配main()。也就是说,改变

const int MAX = 100;
unsigned mp[MAX + 1];

unsigned *mp;

并将main()写为

int main(void)
{
    unsigned n;
    cin >> n;
    mp = new unsigned[n+1];
    mp[0] = n + 1;
    devNum(n, 1);
    delete [] mp;
    return 0;
}