力扣
一.检查相同字母间的距离
1.原题链接:力扣
2.解题思路:
遍历s串,获得每个字符第一次出现的位置,当第二次出现时就直接计算距离;遍历d数组,当a数组和b数组对应值相等或a数组为-1(d可以忽略)时,continue;当a数组不为-1且a数组和b数组对应值不相等,返回 false;当执行完循环结束就返回true
3.参考代码:
class Solution {
public:
bool checkDistances(string s, vector<int>& d) {
int n = s.size();
vector<int>a(26, -1);
for(int i = 0; i < n; i++)
{
int c = s[i]-'a';
if(a[c]==-1)
a[c]=i;
else
a[c]=i-a[c]-1;
}
for(int i = 0; i < 26; i++)
{
if(a[i] == d[i] || a[i]==-1)continue;
if(a[i] != d[i] && a[i]!=-1) return false;
}
return true;
}
};
二.恰好移动K步到达某一位置的方法数目
1.原题链接:力扣
2.解题思路:
设从startPos到endPos为正方向,则从startPos出发,往正方向走了a步,往负方向走了(k - a)步,最后到达endPos,于是有方案数C(k, a),设两点距离为d = abs(endPos - startPos),有等式:a-(k-a)=d,有a=(k+d)/2,于是方案数改写为C(k, (k+d)/2),又有递推式:C(i, j)=C(i-1, j) + C(i-1, j-1),于是可以在k方复杂度下完成计算。
3.参考代码:
class Solution {
public:
const int MOD = 1000000007;
int numberOfWays(int startPos, int endPos, int k) {
int d = abs(endPos - startPos);
if((d + k) % 2 != 0 || d > k) return 0;
vector<vector<long long>> f(k + 1, vector<long long>(k + 1));
for(int i = 0;i <= k;i++) {
f[i][0] = 1;
for(int j = 1;j <= i;j++) {
f[i][j] = (f[i - 1][j] + f[i - 1][j - 1]) % MOD;
}
}
return f[k][(d + k) / 2];
}
};
AcWing
一.火柴棍数字
1.原题链接:4609. 火柴棍数字 - AcWing题库
2.解题思路:
如果n可以被2整除,则输出1;否则输出7;接着再输出n/2 - 1个1即可
3.参考代码:
#include<bits/stdc++.h>
#define int long long
using namespace std;
signed main()
{
int t;
cin >> t;
while(t--){
int n;
cin >> n;
if(n % 2 == 0)cout << 1;
else cout << 7;
for(int i = 1; i < n / 2; i++)cout << 1;
puts("");
}
}
二.列表排序
1.原题链接:4610. 列表排序 - AcWing题库
2.解题思路:
能让所有行都变成目标序列,无非两种情况,要么使用第二个操作,要么不使用;如果使用第二种操作之后符合要求的话, 那么我们每一列都要变成一个相同的且只有一个逆序对的序列,那么这个逆序对有很多种,所以我们先预处理出所有这种序列,然后只要找到一个序列,使得每一行都能在操作次数限制内得到这个序列的话,那么就可行
3.参考代码:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> maps[25];
vector<int> book[200];
int row,col,cnt;
void get_valid()
{
vector<int> tmp(col,0);
for(int i=1;i<=col;i++) tmp[i-1]=i;
book[cnt++]=tmp;
for(int i=0;i<col;i++)
{
for(int j=i+1;j<col;j++)
{
swap(tmp[i],tmp[j]);
book[cnt++]=tmp;
swap(tmp[i],tmp[j]);
}
}
}
bool min_op(vector<int> arr,vector<int> target)
{
if(arr==target) return true;
for(int i=0;i<col;i++)
{
for(int j=i+1;j<col;j++)
{
swap(arr[i],arr[j]);
if(arr==target) return true;
swap(arr[i],arr[j]);
}
}
return false;
}
int main()
{
cin>>row>>col;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
int num;
cin>>num;
maps[i].push_back(num);
}
}
get_valid();
bool flag=false;
for(int i=0;i<cnt;i++)
{
int corr=0;
for(int j=0;j<row;j++)
{
if(min_op(maps[j],book[i]))
{
corr++;
}
}
if(corr==row)
{
flag=true;
break;
}
}
if(flag) cout<<"YES";
else
cout<<"NO";
return 0;
}