C++ 我不知道';我不明白LeetCode上的格雷码的解决方案
以下是描述:C++ 我不知道';我不明白LeetCode上的格雷码的解决方案,c++,algorithm,binary,C++,Algorithm,Binary,以下是描述: ******The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must beg
******The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2
**Note:
For a given n, a gray code sequence is not uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.****
事实上,这一点对我来说是全新的,所以我在WIKI上查看了它的介绍,然后找到了一个解决方案(可能称为镜像构造)
方法),这里有一个关于它的图表:。这种方法有代码编写:
// Mirror arrangement
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res{0};
for (int i = 0; i < n; ++i) {
int size = res.size();
for (int j = size - 1; j >= 0; --j) {
res.push_back(res[j] | (1 << i));
}
}
return res;
}
};
//镜像排列
类解决方案{
公众:
矢量格雷码(整数n){
向量res{0};
对于(int i=0;i=0;--j){
res.push_back(res[j]|(1res.push_back(res[j]|(1)请不要尝试从互联网上的随机代码样本中学习C++。从一本好书中系统地学习它。你对这行的确切理解是什么?“罗恩:格雷码是合理的,而且特定的问题是你对格雷码所期望的那种操作。如果你有问题,我们可以HEL。p和答案。但我们无法帮助您理解。要理解,您必须分而治之。了解向量是什么。了解逻辑or是什么。了解移位运算符的作用。然后将所有内容放在一起,您就会理解。@M将内部FOR block中的句子改为。
res.push_back(res[j] | (1 << i));