题目描述
格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。格雷编码序列必须以 0 开头
链接:https://leetcode-cn.com/problems/gray-code
解题思路
- 数学
https://leetcode-cn.com/problems/gray-code/solution/c5xing-dai-ma-xiang-xi-jie-xi-dui-xin-sh-xrkw/
- 动归(todo)
DFS
class Solution {public:set<string> record;vector<string> ret;void dfs(int count, int n, string str) {if (count==n)return;string curr=str;for (int i=0; i<str.length(); i++) {if (curr[i]=='0') {curr[i]='1';if (record.count(curr)==0)break;curr[i]='0';}else {curr[i]='0';if (record.count(curr)==0)break;curr[i]='1';}}ret.push_back(curr);record.insert(curr);dfs(count+1, n, curr);}int convert(string str, int n) {int num=0;for (int i=0; i<=n; i++) {num += (str[i]-'0') * pow(2, n-i);}return num;}vector<int> grayCode(int n) {string begin = "";for (int i=0; i<n; i++)begin += "0";int Cnt = pow(2, n);record.insert(begin);ret.push_back(begin);dfs(1, Cnt, begin);vector<int> ans;for (auto& str: ret) {//cout << str << " ";ans.push_back(convert(str, n-1));}return ans;}};
