整数划分问题将以正整数n表示成一系列正整数之和.n=n1+n2+n3+...+nk (n1>=n2>=n3>=nk>=1

1个回答

  • 我这里有个C语言的,是输出所有划分的.

    你自己尝试一下改成JAVA的吧.

    #include "stdio.h"

    void main()

    {

    int n;

    scanf("%d",&n);

    if (n == 1)

    {

    printf("1=1n");

    return;

    }

    if (n == 2)

    {

    printf("2=1+1n");

    return;

    }

    int *a = new int(n);

    int top = 0;

    a[0] = n - 1;

    a[1] = 1;

    top = 2;

    int i;

    do{

    printf("%d=%d",n,a[0]);

    for (i = 1; i < top; i++)

    {

    printf("+%d",a[i]);

    }

    printf("n");

    int s = 0;

    do{

    s += a[--top];

    }while (top >= 0 && a[top] == 1);

    if (top == -1)

    {

    break;

    }

    int d = a[top] - 1;

    if (d == 1)

    {

    while (s > 0)

    {

    a[top++] = 1;

    s--;

    }

    }

    else

    {

    do{

    a[top++] = d;

    s -= d;

    }while (s >= d);

    if (s != 0)

    {

    a[top++] = s;

    }

    }

    }while (1);

    }