
Here we will see all possible binary numbers of n bit (n is given by the user) where the sum of each half is same. For example, if the number is 10001 here 10 and 01 are same because their sum is same, and they are in the different halves. Here we will generate all numbers of that type.
Algorithm
genAllBinEqualSumHalf(n, left, right, diff)
left and right are initially empty, diff is holding difference between left and right
艺帆集团公司企业网站源码基于艺帆企业cms制作,全站div+css 制作;它包含了单页设置、单页分类设置、新闻、产品、下载、在线招聘、在线留言、幻灯管理、友情链接管理和数据库备份等功能。 DIV+CSS布局优势一.精简代码,减少重构难度。网站使用DIV+CSS布局使代码很是精简,相信大多朋友也都略有所闻,css文件可以在网站的任意一个页面进行调用,而若是使用table表格修改部分页面却是显得很麻烦
Begin
if n is 0, then
if diff is 0, then
print left + right
end if
return
end if
if n is 1, then
if diff is 0, then
print left + 0 + right
print left + 1 + right
end if
return
end if
if 2* |diff| <= n, then
if left is not blank, then
genAllBinEqualSumHalf(n-2, left + 0, right + 0, diff)
genAllBinEqualSumHalf(n-2, left + 0, right + 1, diff-1)
end if
genAllBinEqualSumHalf(n-2, left + 1, right + 0, diff + 1)
genAllBinEqualSumHalf(n-2, left + 1, right + 1, diff)
end if
EndExample
#includeusing namespace std; //left and right strings will be filled up, di will hold the difference between left and right void genAllBinEqualSumHalf(int n, string left="", string right="", int di=0) { if (n == 0) { //when the n is 0 if (di == 0) //if diff is 0, then concatenate left and right cout << left + right << " "; return; } if (n == 1) {//if 1 bit number is their if (di == 0) { //when difference is 0, generate two numbers one with 0 after left, another with 1 after left, then add right cout << left + "0" + right << " "; cout << left + "1" + right << " "; } return; } if ((2 * abs(di) <= n)) { if (left != ""){ //numbers will not start with 0 genAllBinEqualSumHalf(n-2, left+"0", right+"0", di); //add 0 after left and right genAllBinEqualSumHalf(n-2, left+"0", right+"1", di-1); //add 0 after left, and 1 after right, so difference is 1 less } genAllBinEqualSumHalf(n-2, left+"1", right+"0", di+1); //add 1 after left, and 0 after right, so difference is 1 greater genAllBinEqualSumHalf(n-2, left+"1", right+"1", di); //add 1 after left and right } } main() { int n = 5; genAllBinEqualSumHalf(n); }
输出
100001 100010 101011 110011 100100 101101 101110 110101 110110 111111









