例如以下的格雷码:
具体实现代码如下:
ector<string>::iterator it; vector<string>ans; map<string, int>m; vector<string> getGray(int n) { // write code here string str = ""; for(int i=0; i<n; i++) str += "0"; ans.push_back(str); m[str] = 1; while(1) { int flag = 0; for(int i=n-1; i>=0; i--) { string tmp = str; if(tmp[i] == '0') tmp[i] = '1'; else tmp[i] = '0'; if(!m[tmp]) { flag = 1; str = tmp; ans.push_back(tmp); m[tmp] = 1; break; } } if(!flag) break; } return ans; }