码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]89 Gray Code

时间:2015-01-05 07:12:52      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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]89 Gray Code

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1599091

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!