利用DFS拆分数系列;Depth First Search

利用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;
}

poj2245  Lotto


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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值