Poj Sum It Up

本文介绍了一种使用深度优先搜索算法解决给定目标数与多个正整数之间的组合和问题的方法。通过实例展示如何实现并输出可能的组合方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给出一个目标数t,个数n,以及n个正整数,求出n个数中可能组成的和等于t. , n个数字可不全用。


Sample Input

4 6 4 3 2 2 1 1
5 3 2 1 1
400 12 50 50 50 50 50 50 25 25 25 25 25 25
0 0

Sample Output

Sums of 4:
4
3+1
2+2
2+1+1
Sums of 5:
NONE
Sums of 400:
50+50+50+50+50+50+25+25+25+25
50+50+50+50+50+25+25+25+25+25+25

思路:dfs.....没什么说的

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 15;
int num[maxn];
int tmp[maxn];
int m,n;
bool temp;
void dfs( int sum, int index, int cnt )
{
    if(sum < 0)
        return;
    if( sum == 0 )//一种情况
    {
        temp = 1;//记录  是否输出NONE
        for( int i = 0; i < cnt; i++ )
        {
            if( i == 0 )
            {
                printf("%d", tmp[i]);
            }
            else
            {
                printf("+%d", tmp[i]);
            }
        }
        printf("\n");
        return;
    }
    for( int i = index; i < n; i++ )
    {
        if( i == index || num[i] != num[i-1] )
        {
            tmp[cnt] = num[i];
            dfs( sum - num[i], i + 1, cnt + 1 );//向后退一个元素计算,递归调用
        }
    }
}

int main()
{
    while( scanf("%d%d", &m, &n) && m &&n )
    {
       temp = 0;
        memset( tmp, 0, sizeof( tmp ) );
        for( int i = 0; i < n; i++ )
            scanf("%d", &num[i]);

        printf("Sums of %d:\n", m);
        dfs( m, 0, 0 );
        if( temp != 1 )
            printf("NONE\n");
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值