首页 > 其他 > 详细

LeetCode Gray Code

时间:2015-10-25 09:36:06      阅读:286      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/gray-code/

根据graycode的特性:每次第一位加上一个1,后面是之前结果的倒序,所以从i = 0开始到 i<n, 每次在开头digit加一个新的1, 也就是addNum, 然后从list尾部开始读出数字做计算,在加回到list中去。

n = 0时,[0]

n = 1时,[0,1]

n = 2时,[00,01,11,10]

n = 3时,[000,001,011,010,110,111,101,100]

Time Complexity: O(2^n). Space O(1).

Note: addNum是位移动 i 次,不是len次,len是成指数增长的。

AC Java:

 1 public class Solution {
 2     public List<Integer> grayCode(int n) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         if(n<0){
 5             return res;
 6         }
 7         //when n = 0, return [0]
 8         res.add(0);
 9         for(int i = 0; i<n; i++){
10             int len = res.size();
11             //addNum 是首位要加的1
12             int addNum = 1<<i;
13             for(int j = len-1; j>=0; j--){
14                 res.add(addNum + res.get(j));
15             }
16         }
17         return res;
18     }
19 }

 

LeetCode Gray Code

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4908208.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!