今有7对数字:两个1,两个2,两个3,...两个7,把它们排成一行。
要求,两个1间有1个其它数字,两个2间有2个其它数字,以此类推,两个7之间有7个其它数字。如下就是一个符合要求的排列:17126425374635
当然,如果把它倒过来,也是符合要求的。
请你找出另一种符合要求的排列法,并且这个排列法是以74开头的。
注意:只填写这个14位的整数,不能填写任何多余的内容,比如说明注释等。
74151643752362
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
//按照n = 1~7 进行DFS:每次尝试在当前存在的若干空位放入n,如果可以放,就往下搜索n+1
int num[15]={0,7,4,0,0,0,0,4,0,7,0,0,0,0,0};
void dfs(int n)
{
if(n==4) dfs(n+1);//两个4的位置已经确定,不需要dfs
if(n==7)
{//得到了最终结果,dfs结束
for(int i=1;i<=14;i++) cout<<num[i];
cout<<endl;
return;
}
//dfs 数字 1,2,3,5,6
for(int pos=1;pos<=14;pos++)
{
//1 2 7 9 位置分别放置了 7 4 4 7
if(pos==1 || pos==2 || pos==7 || pos==9) continue;
int bak=pos+n+1;// 当前位置下标 + n个间隔 + 1
if(bak>14) continue;//n的下一个位置越界
if(num[pos]==0 && num[bak]==0)
{//两个位置都还未放置数字
num[pos]=num[bak]=n;
dfs(n+1);
num[pos]=num[bak]=0;//dfs出来,还原初始状态
}
}
}
int main(int argc, char** argv) {
dfs(1);//从数字1开始放置
return 0;
}