Description
What is an integer division? For example, when n=5, we can get the following divisions (note that m>=5 in the example)
5 = 5
= 1 + 4
= 2 + 3
= 1 + 1 + 3
= 1 + 2 + 2
= 1+ 1+ 2
= 1 + 1 + 1 + 1 + 1
Output the number of all divisions
Solution: We can see that the key to the above division is that the number of each division cannot be less than the previous number
Therefore, we can use depth-first search to list all the cases and reduce branches for output.
#include<iostream>
using namespace std;
int Num[100],total=0,N; //total记录总数 Num数组记录划分的情况
void print(int k)
{
int i;
cout<<N<<"="<<Num[1];
for(i=2;i<=k;i++)
cout<<"+"<<Num[i];
cout<<"\n";
total++;
}
void split(int n,int digit) //n是需要拆分的数,dight表示需要拆分的位数
{
if(n<0)
return ;
else if(n==0&&digit>2) //拆分完毕并且拆分的的位数大于1
print(digit-1); //前面digit-1位全部拆分好了
else
{
for(int i=1;i<=n;i++) //从1开始拆分
if(i>=Num[digit-1]) //拆分的数大于或等于前一个数
{
Num[digit]=i; //将这个数计入结果
split(n-i,digit+1); //继续划分 n-i表示剩下的数
Num[digit]=0; //回溯
}
}
}
int main(void)
{
cin>>N;
split(N,1);
cout<<total<<endl;
return 0;
}