LeetCode89/60 Gray Code/Permutation Sequence

一:Leetcode 89Gray Code

题目:The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integernrepresenting the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

For example, givenn= 2, return[0,1,3,2]. Its gray code sequence is:

00 – 001 – 111 – 310 – 2

分析:题目通过分析会发现这样的规律, 比如当有4位时,首先vector中放入一个0(只有0位的时候);然后当位数为1时,vector中存放的是0和1;当位数为2时,vector中存放的是【0,1,3,2】实际上就是加入了3和2,而3==1+2,, 2==0+2;;当位数为3的时候,vector中存放的是【0,1,3,2,6,7,5,4】也就是加入了后4位亦即:6==2+4, 7==3+4,5==1+4,4==0+4.也就是将原有的vector中元素逆序+上当前位所代表的数字(如第三位就是4,第4位就是8等)

代码:

class Solution {public:vector<int> grayCode(int n) {vector<int> result;result.push_back(0);for(int i = 0; i < n; i++){int k = 1 << i;int len = result.size()-1;while(len >= 0){result.push_back(result[len] + k); // 这道题的规律在于数据为从后往前+k放入result中len–;}}return result;}};二:leetcode 60Permutation Sequence

题目:

The set[1,2,3,…,n]contains a total ofn! unique permutations.

By listing and labeling all of the permutations in order,We get the following sequence (ie, forn= 3):

Givennandk, return thekthpermutation sequence.

Note:Givennwill be between 1 and 9 inclusive.

分析:设元素个数为n,那么排名为k,

第1位要放入的元素:j = ceil(k/(n-1)!) ;剩余元素的排名为:k = k- (j-1)*t。。注意这里后续要放入元素并不是j,而是还未被放入的元素中的第j位

代码:

class Solution {public:int factorial(const int &n){int sum = 1;for(int i = 1; i <= n; i++)sum *= i;return sum;}string getPermutation(int n, int k) {string str(n, ' ');int x = k;vector<int> visited;visited.resize(n+1,0);for(int i = 0; i < n; i++){int t = factorial(n-i-1);int j = ceil((x+0.0)/t);/// 未被访问的元素中排名第j个并不是j 放入str[i] ceil是大于等于x = x – (j-1)*t; // 剩余元素所占排名int count = 0;for(int p = 0; p < n; p++){if(!visited[p]) count++;if(count == j){// 未被访问元素中第j个stringstream ss;ss << p+1;ss >> str[i];visited[p] = 1;break;}}}return str;}};

在前进的路上,主动搬开别人脚下的绊脚石,有时往往也是为自己铺路。

LeetCode89/60 Gray Code/Permutation Sequence

相关文章:

你感兴趣的文章:

标签云: