[LeetCode]89. Gray Code
2017-03-27 16:16
483 查看
https://leetcode.com/problems/gray-code/#/description
gray code相邻两个数只有一位不同,求n位数的gray code
结果的前一半最高位为0,后一半最高位为1.再添加新的最高位时只要倒序遍历res,然后把最高位置为1加到res里面即可。
public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList();
if (n < 0) {
return res;
}
res.add(0);
grayCode(n, res, 0);
return res;
}
private void grayCode(int n, List<Integer> res, int index) {
if (n == 0) {
return;
}
for (int i = res.size() - 1; i >= 0; i--) {
res.add(res.get(i) + (1 << index));
}
grayCode(n - 1, res, index + 1);
}
}
gray code相邻两个数只有一位不同,求n位数的gray code
结果的前一半最高位为0,后一半最高位为1.再添加新的最高位时只要倒序遍历res,然后把最高位置为1加到res里面即可。
public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList();
if (n < 0) {
return res;
}
res.add(0);
grayCode(n, res, 0);
return res;
}
private void grayCode(int n, List<Integer> res, int index) {
if (n == 0) {
return;
}
for (int i = res.size() - 1; i >= 0; i--) {
res.add(res.get(i) + (1 << index));
}
grayCode(n - 1, res, index + 1);
}
}
相关文章推荐
- [leetcode] 【数组】 89. Gray Code
- LeetCode | 89. Gray Code
- LeetCode 89. Gray Code
- [leetcode 89] Gray Code
- leetcode[89]Gray Code
- leetcode 刷题之路 89 Gray Code
- LeetCode 89: Gray Code解题报告
- Leetcode 89. Gray Code 格雷码 解题报告
- leetcode题解-89. Gray Code
- LeetCode 89. Gray Code(格雷码)
- LeetCode89——Gray Code
- *LeetCode 89. Gray Code 规律题
- leetcode 89. Gray Code
- Leetcode 89. Gray Code
- (java)leetcode-89:Gray Code
- LeetCode89 Gray Code
- leetcode 89:Gray Code
- LeetCode_89_Gray Code 格雷码
- [leetcode-89]Gray Code(c++)
- LeetCode 89. Gray Code(生成格雷码)