您的位置:首页 > 其它

[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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: