48
//随着n变大,前面的数不用动,后面的数倒着拿出来再在首部加1即可
class Solution {
public:
vector grayCode(int n) {
vector result;
result.push_back(0);
for (int i = 0; i < n; i++) {
const int hight_bit = 1 << i;
for (int j = result.size() - 1; j >= 0; j--) //第二遍反着遍历,形成对称
result.push_back(hight_bit | result[j]);
}
return result;
}
};
编辑于 2016-09-01 20:00:20
回复(7)
17
//LeetCode上的题目,如下
import java.util.*;
public class Solution {
public ArrayList grayCode(int n) {
ArrayList arr = new ArrayList();
int num = 1 << n;
for(int i = 0; i < num; ++i){
arr.add(i>>1^i);
}
return arr;
}
}
发表于 2016-03-26 12:08:09
回复(19)
8
class Solution {
public:
vector grayCode(int n) {
vector result(pow(2,n));
for (int i=1;i<=n;++i)
{
int size = 1<
int flag = 1<
int index = 0;
for (int j=size-1;2*j>=size;--j)
{
result[j] = result[index++]|flag; //左部插入1
}
}
return result;
}
};
当n=1时,为[0,1]
当n=2时,为[00,01,11,10]
当n=3时,为[000,001,011,010,110,111,101,100]
由此可以看出新的序列其实是在前面序列基础上插入新的值
其中前半部分的数值不变,后半部分的数值为上个序列中每个元素第n个位变1,逆向插入
发表于 2016-08-13 21:44:28
回复(1)
3
这道题难在找 dp 方程
先看n=2 (00, 01, 11, 10)
n = 3 ((000, 001, 011, 010), (100,101,111,110))
以此类推, n=k时,就是在n=k-1的前面加上0或者1,然后使得数据扩大2倍
DP转移方程如下:
dp[k] = dp[k-1] | 1<
class Solution {
public:
vector grayCode(int n) {
vector res(1,0);
for(int i=0; i
for(int j=res.size()-1; j>=0; j--){
res.push_back(res[j]|1<
}
}
return res;
}
};
发表于 2018-08-26 09:45:58
回复(0)
2
class S