leetcode 题解: Gray Code
第一眼看到就是枚举,回溯法。
n位的ans就是在n-1的ans的基础上,每一个在首位加上1。
但是有个难点,要保证相邻两数之间只有一位在变化,怎么办?
首先
00
00 01
00 01 11 10
本来是傻乎乎的,直接加的,没有保证只变化1位。
后来发现,从00到01是只变了1位,那么我们给01加上2呢?就变成11, 给00加上2就变成 10。
每次逆序加2^n-1,这样就保证了相邻只变一位。
说不清,基本是蒙对的。碰上了。上代码吧。
- class Solution {
- public:
- vector<int> grayCode(int n) {
- vector<int> ans;
- ans.push_back();
- for(int i=;i<n;i++)
- {
- int len = ans.size();
- for(int j = len-; j >=; j--)
- {
- ans.push_back(ans[j] + pow(,i));
- }
- }
- return ans;
- }
- };
leetcode 题解: Gray Code的更多相关文章
- 【题解】【排列组合】【回溯】【Leetcode】Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit. Given a ...
- [LeetCode] 89. Gray Code 格雷码
The gray code is a binary numeral system where two successive values differ in only one bit. Given a ...
- 【LeetCode】Gray Code
Gray Code The gray code is a binary numeral system where two successive values differ in only one bi ...
- 【leetcode】Gray Code (middle)
The gray code is a binary numeral system where two successive values differ in only one bit. Given a ...
- leetcode[88] Gray Code
题目:格雷码. 格雷码是从0开始且之后两个相邻码之间只有一个符号不相同,例如000,100,101,111三个相邻之间只有一个二进制不同. 现在给定一个数字n,然后给出格雷码所对应的数字.例如: Fo ...
- Java for LeetCode 089 Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit. Given a ...
- leetCode 89.Gray Code (格雷码) 解题思路和方法
The gray code is a binary numeral system where two successive values differ in only one bit. Given a ...
- LeetCode题目:Gray Code
原题地址:https://leetcode.com/problems/gray-code/ class Solution { public: vector<int> grayCode(in ...
- Leetcode#89 Gray Code
原题地址 二进制码 -> 格雷码:从最右边起,依次与左边相邻位异或,最左边一位不变.例如: 二进制: 1 0 0 1 1 1 0 |\|\|\|\|\|\| 格雷码: 1 1 0 1 0 0 1 ...
- [LeetCode]题解(python):089 Gray Code
题目来源 https://leetcode.com/problems/gray-code/ The gray code is a binary numeral system where two suc ...
随机推荐
- CSDN也有我的博客啦
我的CSDN:https://blog.csdn.net/qq_40875849
- vm 虚拟机选择启动项
1. 每次狂按鼠标和ESC而且要试验N次,找了一下解决办法 在你的虚拟机里面找到一个 .vmx文件(虚拟机初始化文件) 加入 bios.bootDelay = "5000"(延迟 ...
- 基于folly的AtomicIntrusiveLinkedList无锁队列进行简单封装的多生产多消费模型
1.基于folly的AtomicIntrusiveLinkedList略微修改的无锁队列代码: #ifndef FOLLY_REVISE_H #define FOLLY_REVISE_H namesp ...
- [UE4]计算AimOffset偏移动画的角度
- C# DataReader
//1 连接字符串 string connectionString = "server=127.0.0.1;integrated security=true;database=MSPetSh ...
- BCGcontrolBar(六) RibbonBar编辑
BCGcontrolBar 可以使用 Ribbon Designer方便的对 Ribbon条进行编辑 文件位置为 C:\Program Files\BCGSoft\BCGControlBarPro\D ...
- OpenCV-Python基本功能
一.图像读取/保存 import cv2 img = cv2.imread("name.png") cv2.imwrite('save.jpg', img) #显示图像 cv2.i ...
- Codeforces Round #492 (Div. 2)
A. /* 从大往小依次除 */ #include<cstdio> #include<algorithm> #include<cstring> #include&l ...
- 初级安全入门—— WEBshell与文件上传漏洞
概念介绍 WebShell网页木马文件 最常见利用文件上传漏洞的方法就是上传网站木马(WebShell)文件,根据开发语言的不同又分为ASP木马.PHP木马.JSP木马等,该木马利用了脚本语言中的系统 ...
- spring揭密学习笔记(3)-spring ioc容器:Spring的IoC容器之BeanFactory
1. Spring的IoC容器和IoC Service Provider的关系 Spring的IoC容器和IoC Service Provider所提供的服务之间存在一定的交集,二者的关系如图4-1所 ...