利用DFS的递归回溯的性质进行数的拆分:
样例输入
-
5
样例输出
-
5=1+1+1+1+1 5=1+1+1+2 5=1+1+3 5=1+2+2 5=1+4 5=2+3
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <iomanip>
#include <list>
#include <queue>
#include <stack>
using namespace std;
int number[100];
void number_split(int n,int reminder,int depth,int last)
{
if(reminder==0)
{
if(depth!=2)
{
printf("%d=",n);
for(int j=1;j<depth;j++)
{
printf("%d%c",number[j],j==depth-1?'\n':'+');
}
}
}
for(int i=last;i<=reminder;i++)
{
number[depth]=i;
number_split(n,reminder-i,depth+1,i);
}
}
int main()
{
int n;
while(cin>>n)
{
number_split(n,n,1,1);
}
return 0;
}
dfs里面,last表示的是a[ ]里面用到的最后的数的下标,depth表示的是ans[ ]的长度,也是下标;
//#include <bits/stdc++.h>
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=100000+10;
int ans[maxn/100];
int a[maxn/100];
void dfs(int n,int last,int depth)//last记录的是最后的那个数a[]的下标,depth记录的是ans[]下标数组的
{
if(depth == 7)
{
for(int i=1; i<=6; i++)
{
if(i<6)
cout<<ans[i]<<" ";
else cout<<ans[i]<<endl;
}
return ;
}
for(int i=last+1;i<= n; i++)
{
ans[depth] = a[i];
dfs(n,i,depth+1);
}
}
int main()
{
int n;
while(~scanf("%d",&n) && n)
{
for(int i = 1;i <= n;i++)
scanf("%d",&a[i]);
dfs(n,0,1);
cout<<endl;
}
return 0;
}