问题描述:

One curious child has a set of N little bricks. From these bricks he builds different staircases. Staircase consists of steps of different sizes in a strictly descending order. It is not allowed for staircase to have steps equal sizes. Every staircase consists of at least two steps and each step contains at least one brick. Picture gives examples of staircase for N=11 and N=5:

Your task is to write a program that reads from input numbers N and writes to output numbers Q - amount of different staircases that can be built from exactly N bricks. 

Input 
Numbers N, one on each line. You can assume N is between 3 and 500, both inclusive. A number 0 indicates the end of input. 

Output 
Numbers Q, one on each line. 

Sample Input 
3 
5 
0 

Sample Output 
1 
2 

Problem Source: Zhejiang University Local Contest 2002, Warmup 

解题:

先假设a[i][i] = 1, a[i][j]代表i分成最大值小于等于j的种类,于是有更简单的递推式: a[i][j] = a[i-j][j-1] + a[i][j-1], 前为包含j的情况,后为不包含 并且在此基础上,这里使用备忘录方法

#include <cstdio> 
#include <string> 
#define MAXLEN 501 
double a[MAXLEN][MAXLEN]; 
double GetA( int i, int j); 

int main() 
{ 
    int i, n; 
    memset(a,-1,sizeof(a)); 
    a[0][0] = 1; 
    for ( i=1; i<MAXLEN; i++ ) 
    { 
        /* 初始化完成,只初始化用到的,a[0][i] = 1; a[i][0]=0,i>0 */ 
        a[i][0] = 0; 
        a[0][i] = 1; 
    }

    while(scanf("%d", &n) && n) 
    {   
    printf("%0.0f\n", GetA(n,n) - 1);/* 调用即备忘 */ 
    } 
    return 0; 
} 

double GetA( int i, int j) 
{ 
    /* 分几种情况讨论a[i][j] */ 
    if ( a[i][j] >= 0 ) 
        return a[i][j]; 
    if ( i < j ) 
        return a[i][j] = GetA( i, i ); 
    if ( i>=j && j>0 ) 
        return a[i][j] = GetA(i-j,j-1) + GetA(i,j-1); 
    else 
        return -1; 
}