Skip to content

Commit 726d4e1

Browse files
committed
day 1
1 parent 5163141 commit 726d4e1

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

Diff for: Leetcode Daily Challenge/July-2021/01. Gray Code.cpp

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Gray Code
3+
=========
4+
5+
An n-bit gray code sequence is a sequence of 2n integers where:
6+
7+
Every integer is in the inclusive range [0, 2n - 1],
8+
The first integer is 0,
9+
An integer appears no more than once in the sequence,
10+
The binary representation of every pair of adjacent integers differs by exactly one bit, and
11+
The binary representation of the first and last integers differs by exactly one bit.
12+
Given an integer n, return any valid n-bit gray code sequence.
13+
14+
Example 1:
15+
Input: n = 2
16+
Output: [0,1,3,2]
17+
Explanation:
18+
The binary representation of [0,1,3,2] is [00,01,11,10].
19+
- 00 and 01 differ by one bit
20+
- 01 and 11 differ by one bit
21+
- 11 and 10 differ by one bit
22+
- 10 and 00 differ by one bit
23+
[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].
24+
- 00 and 10 differ by one bit
25+
- 10 and 11 differ by one bit
26+
- 11 and 01 differ by one bit
27+
- 01 and 00 differ by one bit
28+
29+
Example 2:
30+
Input: n = 1
31+
Output: [0,1]
32+
33+
Constraints:
34+
1 <= n <= 16
35+
*/
36+
37+
class Solution
38+
{
39+
public:
40+
vector<int> grayCode(int n)
41+
{
42+
if (n == 1)
43+
return {0, 1};
44+
auto prev = grayCode(n - 1);
45+
auto ans = prev;
46+
47+
for (int i = prev.size() - 1; i >= 0; --i)
48+
{
49+
int num = prev[i] + pow(2, n - 1);
50+
ans.push_back(num);
51+
}
52+
53+
return ans;
54+
}
55+
};

Diff for: Leetcode Daily Challenge/July-2021/README.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# June 2021 LeetCoding Challenge
2+
3+
| Day | Question Links | Solutions |
4+
| :-: | :------------------------------------------------------------------------------------------------------------------------- | :----------------------------: |
5+
| 1. | [Gray Code](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge-2021/608/week-1-july-1st-july-7th/3799/) | [cpp](./01.%20Gray%20Code.cpp) |

Diff for: Leetcode Daily Challenge/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@
1414
- [April](./April-2021)
1515
- [May](./May-2021)
1616
- [June](./June-2021)
17+
- [July](./July-2021)

0 commit comments

Comments
 (0)