计蒜课 挑战难题 组合运算式

本文介绍了一种算法,用于寻找由1至N的整数组成的递增数列,在每对数字间插入“+”、“-”或“”后能得到和为零的所有可能数列。文章提供了一个C++实现示例,通过递归方法遍历所有可能的组合。

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

                            41次
  • 34.15%
  • 1000ms
  • 65536K

    请考虑一个被空格分隔的,由1到N的整数组成的递增数列:1 2 3 ... N。现在请在数列中插入表示加的“+”,或者表示减“-”,亦或者表示空白的“ ”(例如1-2 3就等于1-23),来将每一对数字组合成一个表达式(第一个数字前无空格)。计算该表达式的结果并判断其值是否为0。请你写一个程序找出所有产生和为零的长度为N的数列。

    输入为一行,包含一个整数N(3≤N≤9)。

    输出为所有在每对数字间插入“+”, “-”, 或 “ ”后能得到和为零的数列,并按照字典(ASCII码)序排列。

    样例1

    输入:

    7

    输出:

    1+2-3+4-5-6+7
    1+2-3-4+5+6-7
    1-2 3+4+5+6+7
    1-2 3-4 5+6 7
    1-2+3+4-5+6-7
    1-2-3-4-5+6+7
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    using namespace std;
    const int maxn = 10;
    int fa[maxn];
    
    void dfs(int cur,int n)
    {
        if(cur == n+1)
        {
            int sum = 0;
            int temp = 1;
            int x = 1;
            for(int i = 2; i <= n; i++)
                if(fa[i] == 1)
                {
                    if(x == 1)
                        sum += temp;
                    else
                        sum -= temp;
                    temp = i;
                    x = 1;
                }
                else if(fa[i] == 2)
                {
                    if(x == 1)
                        sum += temp;
                    else
                        sum -= temp;
                    temp = i;
                    x = 2;
                }
                else
                    temp = temp*10+i;
                if(x == 1)
                    sum += temp;
                else
                    sum -= temp;
            if(!sum)
            {
                printf("1");
                for(int i = 2; i <= n; i++)
                    if(fa[i] == 1)
                        printf("+%d", i);
                    else if(fa[i] == 2)
                        printf("-%d", i);
                    else if(fa[i] == 3)
                        printf(" %d", i);
                printf("\n");
            }
            return ;
        }
        fa[cur] = 3;
        dfs(cur+1, n);
        fa[cur] = 1;
        dfs(cur+1, n);
        fa[cur] = 2;
        dfs(cur+1, n);
    }
    
    int main()
    {
        int n;
        while(scanf("%d", &n) != EOF)
        {
            memset(fa,0,sizeof(fa));
            dfs(2,n);
        }
        return 0;
    }
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值