首页 > 其他 > 详细

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

时间:2015-11-13 22:09:40      阅读:314      评论:0      收藏:0      [点我收藏+]

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

  技术分享

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

原文:http://www.cnblogs.com/yxk529188712/p/4963256.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!