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

  

posted on 2015-11-13 21:13  Linux-ever  阅读(810)  评论(0编辑  收藏  举报