這將做到這一點:
#include <iostream>
#include <vector>
using namespace std;
vector<unsigned int> foo(unsigned int n)
{
vector<unsigned int> ans;
// One of the combinations is not to change anything, i.e. number itself
ans.push_back(n);
for(unsigned int i = 0; i < 32; i++) {
// Combinations with only one bit changed
ans.push_back(n^(1 << i));
for(unsigned int j = 0; j < i; j++) {
// Combinations with two bits changed
ans.push_back(n^(1 << i)^(1 << j));
}
}
return ans;
}
int main()
{
vector<unsigned int> v = foo(0);
for(unsigned int i = 0; i < v.size(); i++) {
cout << v[i] << endl;
}
return 0;
}
附:
#include <iostream>
#include <vector>
using namespace std;
/*
start denotes bit number from which we should start loop, i.e. we can't
modify any bits before that bit to avoid duplicates (we are modifying bits
with order from lowest to highest, so if we have modified some bit, next bit
to modify should be a higher one.
*/
void foo(vector<unsigned int>& ans, unsigned int number, int n, unsigned int start)
{
// As we reached to current number someway then it is one of the combinations
ans.push_back(number);
if(n < 1) {
// No more changes allowed, go back
return;
}
// Try change one bit
for(unsigned int i = start; i < 32; i++) {
foo(ans, number^(1 << i), n - 1, i + 1);
}
}
int main()
{
vector<unsigned int> v;
unsigned int startingNumber = 0;
int changesAllowed = 2;
foo(v, startingNumber, changesAllowed, 0);
for(unsigned int i = 0; i < v.size(); i++) {
cout << v[i] << endl;
}
return 0;
}
你真正需要的可能變化的名單(從00000000我想)或檢查給定數目是否在允許的變化(從00000000)的函數: 這裏是根據描述的變化修改後的代碼? – 2013-03-07 08:43:09
如果你只是需要一個函數來計算[兩個二進制字符串的漢明距離](http://en.wikipedia.org/wiki/Hamming_distance#Special_properties),而你是一個現代的X86處理器,你可能想看看在[POPCNT](http://en.wikipedia.org/wiki/SSE4#POPCNT_and_LZCNT)指令(與異或) – 2013-03-07 08:47:07
關於可能的組合數,實際上它不是C(32,2)* 4注意到,因爲你也計算了重複。組合的實數將是1 + 32 + C(32,2),這3個部分中的每一個分別表示沒有變化,1位變化和2位變化的組合。 – aram90 2013-03-07 10:38:42