[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; } }
相关文章推荐
- LeetCode89 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(生成格雷码)
- Leetcode 89 Gray Code
- 【Leetcode】:89. Gray Code 问题 in JAVA
- leetcode89-Gray Code(格雷码)
- leetcode 89. Gray Code 按照index递归DFS解决 + Grey码生成公式 + 位运算直接计算
- 【Leetcode】89. Gray Code 【递归】
- [leetcode] 89. Gray Code 解题报告
- leetcode 89:Gray Code
- 【leetcode】89. Gray Code【java】
- leetcode[89]Gray Code
- 【leetcode】【89】Gray Code
- [leetcode 89] Gray Code