2778 - 数的拆分

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 128 MB

任何一个大于1的自然数n,总可以拆分成若干个小于n的自然数之和。当n=7,共有14种拆分方法:

题目输入

输入1行:整数n。

题目输出

输出多行:每一行表示一种拆分方案,最后一行输出方案总数。

输入/输出样例

输入格式

7

输出格式

7=1+1+1+1+1+1+1
7=1+1+1+1+1+2
7=1+1+1+1+3
7=1+1+1+2+2
7=1+1+1+4
7=1+1+2+3
7=1+1+5
7=1+2+2+2
7=1+2+4
7=1+3+3
7=1+6
7=2+2+3
7=2+5
7=3+4
14

C语言解答

#include<stdio.h>
#include<stdlib.h>
int a[20]={1};
int n,tot=0;
void out(int i){
     int j;
     printf("%d=",n);
     for(j=1;j<i;j++)
         printf("%d+",a[j]);
     printf("%d\n",a[i]);
}

void search(int i,int s){
     int j;
     for(j=a[i-1];j<=s;j++)
        if(j<n) {
          a[i]=j;
          s-=j;
          if(s==0){
		  out(i);
		  tot++;
		  }
          else search(i+1,s);
          s+=j;
          }
}

int main(){
    scanf("%d",&n);
    search(1,n);
    printf("%d",tot);

}

C++解答

#include<cstdio>
#include<iostream>
#include<cstdlib>

using namespace std;

int a[10001]={1},n,total;
int search(int,int);
int print(int);
int main()
{
	cin >> n;
	
	search(n,1);
	
	cout << total;
	
	return 0;
}
int search(int s,int t)
{
	int i;
	for(i=a[t-1];i<=s;i++)
	 if(i<n)
	 {
	 	a[t]=i;
	 	s-=i;
	 	if(s==0)print(t);
	 	else search(s,t+1);
	 	s+=i;
	 }
}
int print(int t)
{
	cout << n << "=";
	
	for(int i=1;i<=t-1;++i)
	  cout << a[i] << "+";
	 cout << a[t] <<endl;
	
	total++;
}