标签:
原题链接在这里: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 }
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4908208.html