最初毫无思路,看了下网上的解答豁然开朗.....观察发现格雷码是有规律的.....根据首位不同,n的格雷码可以分为两部分(前一半首位为0,后一半首位为1):
1. 首位为0,前一半的格雷码等于(n-1)的格雷码(首位多加个0,但不影响值);
2. 首位为1,后n-1位相当于前一半后n-1位(即n-1的格雷码)的倒序....
因而我们可以递归获取n-1的格雷码先存入res,再倒序选择首位加一存入res即可
public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<Integer>();
if(n==0)
{
res.add(0);
return res;
}
List<Integer> tmp = grayCode(n-1);
int firstCode = 1<<(n-1);
res = new ArrayList<Integer>(tmp);
for(int i=tmp.size()-1;i>=0;i--)
{
int highTmp = firstCode+tmp.get(i);
res.add(highTmp);
}
return res;
}
}
本文介绍了一种递归生成格雷码的算法。通过将问题分解为两部分,利用已知n-1的格雷码生成n的格雷码,提高了算法效率。详细解释了首位为0和1时的处理方式。
6615

被折叠的 条评论
为什么被折叠?



