计算1-9总共九个数字可以满足abc+def=hij这样的式子

计算1-9总共九个数字可以满足abc+def=hij这样的式子;其中abcdefghij九个数字各个都不相同,它们都属于1-9个数字中;

首先,第一种方法很简单很暴力,直接枚举,这样的话时间复杂度高;

这种题其实和上一篇对1-num个数字进行全排列是一样的,只不过现在对排列加了一个条件abc+def=hij;

那么有深度优先遍历很简单,还是递归的思想;

/*************************************************************************
	> File Name: sum.cpp
	> Author: 
	> Mail: 
	> Created Time: 2015年11月13日 星期五 20时34分23秒
 ************************************************************************/

#include<iostream>
using namespace std;
const int MAXNUM = 10;
int box[MAXNUM];
int book[MAXNUM];
int count = 0;

void dfs(int step)
{
    if (step == MAXNUM){
        if (box[1]*100+box[2]*10+box[3] + box[4]*100+box[5]*10+box[6] == box[7]*100+box[8]*10+box[9]){
            cout << box[1] << box[2] << box[3] << "+" << box[4] << box[5] << box[6] << "=" 
                << box[7] << box[8] << box[9] << endl;
            count++;
        }
        
        return;
    }

    for (int i = 1; i < MAXNUM; i++){
        if(book[i] == 0){
            box[step] = i;
            book[i] = 1; 
            dfs(step+1);
            book[i] = 0;
        }
    }
    return;
}

int main()
{
    dfs(1);
    
    cout << "There has " << count << " results." << endl;
    return 0;
}

  

转载于:https://www.cnblogs.com/yxk529188712/p/4963256.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值