FTPrep, 89 Gray Code

来源:互联网 发布:如何成为淘宝超级会员 编辑:程序博客网 时间:2024/06/06 03:56

这道题 其实很算法的关系不大,更重要的是找到格雷码的形成规律。

规律入下:

1,base case:0,1

2,f: g(x) --> g(x+1), 相当于把g(x)里的元素逆序遍历,同时加上 1<<(x),就得到了list中要添加的数。

1&2就说明了list的形成过程了。每一次+1有一个for,每一个for里要对之前的list进行遍历,又多了一个for,两个for搞定。

代码如下:

class Solution {    public List<Integer> grayCode(int n) {        List<Integer> result = new ArrayList<Integer>();        if(n<0) return result;        if(n==0){            result.add(0);            return result;        }        if(n==1){            result.add(0);            result.add(1);            return result;        }        result.add(0);        result.add(1);  // the following adding is based on the existing numbers, so need to add the basis, for populating!!        for(int bitNum=2; bitNum<=n; bitNum++){            int last= result.size()-1;  // every iteration, the result gets double in size, need to get the fixed index            // since the size is growing when adding new elems.            int numForBit= 1<<(bitNum-1);            for(int index=last; index>=0; index--){   // populate from the existing base, BACKWARD!!                result.add(result.get(index)+numForBit);  // since 1 is already the 1st bit, so need to move (bitNum-1)            }        }        return result;            }}


原创粉丝点击