File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
basic-learning/src/main/java/com/jacobs/basic/algorithm/leetcode Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1
1
package com .jacobs .basic .algorithm .leetcode ;
2
2
3
+ import java .util .ArrayList ;
4
+ import java .util .Arrays ;
5
+ import java .util .List ;
6
+
3
7
/**
4
8
* @author lichao
5
9
* Created on 2019-06-22
@@ -170,4 +174,34 @@ public int removeDuplicates2(int[] nums) {
170
174
nums [i ++] = n ;
171
175
return i ;
172
176
}
177
+
178
+ /**
179
+ * leetcode 89
180
+ *
181
+ * 格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
182
+ * 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。
183
+ *
184
+ * 输入: 2
185
+ * 输出: [0,1,3,2]
186
+ * 解释:
187
+ * 00 - 0
188
+ * 01 - 1
189
+ * 11 - 3
190
+ * 10 - 2
191
+ * @param n
192
+ * @return
193
+ */
194
+ public List <Integer > grayCode (int n ) {
195
+ if (n == 0 ) {
196
+ return Arrays .asList (0 );
197
+ }
198
+ List <Integer > prev = grayCode (n - 1 );
199
+ List <Integer > next = new ArrayList <Integer >(prev );
200
+ int pow = 1 << (n - 1 );
201
+ for (int i = prev .size () - 1 ; i >= 0 ; i --) {
202
+ // 对前面得到的每一项在高位加上1,生成新的一项
203
+ next .add (prev .get (i ) | pow );
204
+ }
205
+ return next ;
206
+ }
173
207
}
You can’t perform that action at this time.
0 commit comments