class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for(int i=0;i<n;++i)
dp[i][i] = 1;
for(int sz = 2; sz <= n;++sz)
{
for(int i=0, j=sz-1;j<n;++i, ++j)
{
if(s[i]==s[j])
dp[i][j] = dp[i+1][j-1] + 2;
else
dp[i][j] = max(dp[i+1][j], dp[i][j-1]);
}
}
return dp[0][n-1];
}
};
若G
为格雷码,B
为二进制数,则有如下转换公式
G
转B
:
G = x o r ( B , B > > 1 ) G = xor(B, B>>1) G=xor(B,B>>1)
B
转G
,其中i
为二进制位数:
B n − 1 = G n − 1 B i = x o r ( B i + 1 , G i ) i = 0 , 1 , 2 … … n − 2 \begin{aligned} &B_{n-1} = G_{n-1}\\ &B_i = xor(B_{i+1}, G_i) \quad i=0,1,2……n-2\\ \end{aligned} Bn−1=Gn−1Bi=xor(Bi+1,Gi)i=0,1,2……n−2
class Solution
{
public:
vector<int> circularPermutation(int n, int start)
{
vector<int> v = { start };
int b = start;
while (start >>= 1)
b ^= start;
n = (1 << n) - 1;
for (int i = 1; i <= n; i++)
v.push_back(b + i & n ^ (b + i & n) >> 1);
return v;
}
};
这里要注意一下,我们要以素数序列为基准扫描而不要以dp数组为基准扫描,dp数组可能会非常大导致超时。
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
vector<int> dp(n, numeric_limits<int>::max()), index(primes.size(), 0);
dp[0] = 1;
for(int i=1;i<n;++i)
{
for(int j=0;j<primes.size();++j)
{
dp[i]=min(dp[i], dp[index[j]] * primes[j]);
}
for(int j=0;j<primes.size();++j)
{
if(dp[i]/primes[j] == dp[index[j]])
++index[j];
}
}
return dp[n-1];
}
};
class Solution {
public:
vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) {
array<int, 4> dr={0, 1, 0, -1}, dc = {1, 0, -1, 0};
vector<vector<int>> res;
res.push_back(vector<int>{r0, c0});
if(R*C == 1)
return res;
for(int k=1; k<2*(R+C); k+=2)
{
for(int i=0;i<4;++i)
{
int step = k + i/2;
for(int j=0;j<step;++j)
{
r0 += dr[i];
c0 += dc[i];
if(r0>=0&&r0<R&&c0>=0&&c0<C)
res.push_back(vector<int>{r0, c0});
}
}
}
return res;
}
};
class Solution {
public:
double nthPersonGetsNthSeat(int n) {
if(n==1)
return 1;
else
return 1.0/n + double(n-2)/n * nthPersonGetsNthSeat(n-1);
}
};
class Solution {
public:
vector<int> pathInZigZagTree(int label) {
int h = int(log(label)/log(2)) + 1;
int ori = (h&1)>0?label:((1<<(h-1))+(1<<h)-1-label);
vector<int> res;
while(h > 0)
{
res.push_back((h&1)>0?ori:((1<<(h-1))+(1<<h)-1-ori));
ori>>=1;
--h;
}
reverse(res.begin(), res.end());
return res;
}
};