您的位置:首页 > 其它

[LeetCode]89 Gray Code

2015-01-04 18:43 267 查看
https://oj.leetcode.com/problems/gray-code/
public class Solution {
public List<Integer> grayCode(int n)
{
// 规律:
// n = 0:
// 0
//
// n = 1:
// 0
// 1
//
// n = 2:
// 00
// 01
// 11
// 10
//
// n = 3
// 000
// 001
// 011
// 010
// 110
// 111
// 101
// 100
//
// 设 n-1 结果集 为 s
// 正序 每一个 i,头部加入 0,放入新结果集
// 倒序 每一个 i,头部加入 1,放入新结果集

if (n < 0)
return Collections.emptyList();

if (n == 0)
return Collections.singletonList(0);

List<String> str = code(n);
List<Integer> toReturn = new ArrayList<>();
for (String s : str)
{
toReturn.add(Integer.parseInt(s, 2));
}
return toReturn;
}

private List<String> code(int n)
{
if (n == 1)
{
List<String> toReturn = new ArrayList<>();
toReturn.add("0");
toReturn.add("1");
return toReturn;
}

List<String> last = code(n - 1);
List<String> toReturn = new ArrayList<>();
// for each e in last, append 0, to head. and into new result
for (String s : last)
{
toReturn.add("0" + s);
}
// for each e in last (reverse), and append (1) in it.
for (int i = last.size() - 1 ; i >= 0 ; i --)
{
toReturn.add("1" + last.get(i));
}
return toReturn;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode