#Success
Details
Runtime: 54 ms, faster than 14.20% of Java online submissions for Gray Code.
Memory Usage: 55 MB, less than 20.55% of Java online submissions for Gray Code.
class Solution {
void dfs(List<String> al, String mostSignificantBit){
if (mostSignificantBit.equals("0")){
for (int i=0;i<al.size();i++)
al.set(i, mostSignificantBit + al.get(i));
}
else{
Collections.reverse(al);
for (int i=0;i<al.size();i++)
al.set(i, mostSignificantBit + al.get(i));
}
}
public List<Integer> grayCode(int n) {
List<String> strings = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();
//list in which all strings have as most significant bit the one
List<String> listWithOne = new ArrayList<>();
//all strings have as significant bit the zero
List<String> listWithZero = new ArrayList<>();
strings.add("");
for (int i=1;i<=n;i++){
listWithOne.addAll(strings);
listWithZero.addAll(strings);
dfs(listWithZero, "0");
dfs(listWithOne, "1");
//System.out.println("zero:" + listWithZero);
//System.out.println("one:" + listWithOne);
strings.clear();
strings.addAll(listWithZero);
strings.addAll(listWithOne);
listWithZero.clear();
listWithOne.clear();
}
for (String numStr:strings){
int num = 0;
for (int i=0;i<numStr.length();i++){
int value = numStr.charAt(i) - '0';
num += (int)Math.pow(2,n-1-i)*value;
}
numbers.add(num);
}
return numbers;
}
}
An n-bit gray code sequence is a sequence of 2n integers where:
Every integer is in the inclusive range [0, 2n - 1],
The first integer is 0,
An integer appears no more than once in the sequence,
The binary representation of every pair of adjacent integers differs by exactly one bit, and
The binary representation of the first and last integers differs by exactly one bit.
Given an integer n, return any valid n-bit gray code sequence.
Example 1:
Input: n = 2
Output: [0,1,3,2]
Explanation:
The binary representation of [0,1,3,2] is [00,01,11,10].
- 00 and 01 differ by one bit
- 01 and 11 differ by one bit
- 11 and 10 differ by one bit
- 10 and 00 differ by one bit
[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].
- 00 and 10 differ by one bit
- 10 and 11 differ by one bit
- 11 and 01 differ by one bit
- 01 and 00 differ by one bit