HNUOJ_10074

Adding 1s, 2s, and 3s
Time Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:32768KB
Total submit users: 854, Accepted users: 813
Problem 10074 : No special judgement
Problem description
Integer 4 can be expressed as a sum of 1s, 2s, and 3s in seven different ways as follows:
        1+1+1+1, (1)
        1+1+2, (2)
        1+2+1, (3)
        2+1+1, (4)
        2+2, (5)
        1+3, (6)
        3+1. (7)
Write a program that determines the number of ways in which a given integer can be expressed as a sum of 1s, 2s, and 3s. You may assume that the integer is positive and less than 20.
Input
The input consists of T test cases. The number of test cases (T ) is given in the first line of the input file. Each test case consists of an integer written in a single line.
Output
Print exactly one line for each test case. The line should contain an integer representing the number of ways.
Sample Input
3
4
7
10
Sample Output
7
44
274
Problem Source
SJTU2004

公式:f(n)=f(n-3)+f(n-2)+f(n-1)

运用推导出来的公式直接解决:

#include<stdio.h>
int main()
{
	int i,j,n;
	int f[21]={1,1,2};
	for(i=3;i<21;i++)
	{
		f[i]=f[i-1]+f[i-2]+f[i-3];
	}
	scanf("%d",&j);
	while(j--)
	{
		scanf("%d",&n);
		printf("%d\n",f[n]);
	};
	return 0;
}

运用递归方式解决:

#include<stdio.h> 
int s;
void f(int n)
{ 
    int i;
    if(!n)              //如果n为0,则递归结束,返回上一级,同时总数加1
    {
        s++;
        return;
    }
    for(i=n<3?n:3;i!=0;i--)    //重点!如果n此时大于等于3,则令i=n,否则i=n;然后令i递减至0,每次都递归调用f(n-i)
        f(n-i);
} 
int main()
{ 
    int i,t,x; 
    scanf("%d", &t);       //读取一共有T个数字
    for(i=t;i>0;i--)       //循环读取这T个数字,每次读取一个,读取完后立即处理并输出
    { 
        scanf("%d", &x);   //读取当前要处理的数字
        s=0;               //拆分方法总数置零
        f(x);              //计算
        printf("%d\n", s); //输出这个数字的拆分方法总数
    }
	return 0; 
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值