计蒜客 组合运算式(简单DFS)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37960603/article/details/82252827

题目传送门
代码:

#include<bits/stdc++.h>
using namespace std;

int n;
int type[10];

void DFS(int v,int s,int pre,int ty){

    if(v==n){

        if(s==0){

            printf("1");
            for(int i=2;i<=n;i++){

                if(type[i]==2) printf("+%d",i);
                else if(type[i]==1) printf("-%d",i);
                else printf(" %d",i);
            }
            printf("\n");
        }
        return ;
    }
    for(int i=3;i>=1;i--){

        type[v+1]=i;
        if(i==2) DFS(v+1,s+v+1,v+1,i);
        else if(i==1) DFS(v+1,s-v-1,v+1,i);
        else{

            if(ty==2) DFS(v+1,s-pre+pre*10+(v+1),pre*10+(v+1),ty);
            else if(ty==1) DFS(v+1,s+pre-pre*10-(v+1),pre*10+(v+1),ty);;
        }
    }
}

int main(){

    scanf("%d",&n);
    DFS(1,1,1,2);
}

猜你喜欢

转载自blog.csdn.net/qq_37960603/article/details/82252827
今日推荐