1.算数三元组的数目
题意:
思路:
简单的三重循环判断条件是否成立记录答案
Code
class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
int res = 0;
for (int i = 0; i < nums.size(); i++)
for (int j = i + 1; j < nums.size(); j++)
for (int k = j + 1; k < nums.size(); k++)
if (nums[j] - nums[i] == diff && nums[k] - nums[j] == diff)
res ++;
return res;
}
};
2.受限条件下可到达节点的数目
题意:
思路:
d f s dfs dfs返回可到达的点总数
Code
class Solution {
public:
int reachableNodes(int n, vector<vector<int>>& edges, vector<int>& restricted) {
vector<int> vis(n);
for (auto it : restricted)
vis[it] = 1;
vector<int> e[n];
for (auto it : edges) {
e[it[0]].push_back(it[1]);
e[it[1]].push_back(it[0]);
}
function<int(int)> dfs = [&] (int u) {
int ans = 1;
vis[u] = 1;
for (auto it : e[u]) {
if (!vis[it])
ans += dfs(it);
}
return ans;
};
return dfs(0);
}
};
3.检查数组是否存在有效划分
题意:
思路:
动态规划
状态表示: f ( i ) f(i) f(i)表示是否从 i i i开始新的划分, f ( i ) = 1 f(i) = 1 f(i)=1表示 i i i之前都有合法划分方案
状态转移: f ( i + 2 ) = n u m s [ i ] = = n u m s [ i + 1 ] , f ( i + 3 ) = n u m s [ i ] = = n u m s [ i + 1 ] & & n u m s [ i + 2 ] = = n u m s [ i ] ∣ ∣ n u m s [ i ] + 1 = = n u m s [ i + 1 ] & & n u m s [ i ] + 2 = = n u m s [ i + 2 ] f(i + 2) = nums[i] == nums[i + 1],f(i+3) = nums[i] == nums[i+1] \&\& nums[i+2] == nums[i] || nums[i] + 1 == nums[i + 1] \&\& nums[i] + 2 == nums[i + 2] f(i+2)=nums[i]==nums[i+1],f(i+3)=nums[i]==nums[i+1]&&nums[i+2]==nums[i]∣∣nums[i]+1==nums[i+1]&&nums[i]+2==nums[i+2]
Code
class Solution {
public:
bool validPartition(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n + 1);
dp[0] = 1;
for (int i = 0; i < n; i++) {
if (dp[i]) {
if (i + 2 <= n && nums[i] == nums[i + 1]) {
dp[i + 2] = 1;
}
if (i + 3 <= n && nums[i] + 1 == nums[i + 1] && nums[i + 2] == nums[i] + 2) {
dp[i + 3] = 1;
}
if (i + 3 <= n && nums[i] == nums[i + 1] && nums[i] == nums[i + 2]) {
dp[i + 3] = 1;
}
}
}
return dp[n];
}
};
4.最长理想子序列
题意:
思路:
动态规划
状态表示: f ( i ) f(i) f(i)表示以 s [ i ] s[i] s[i]结尾的子序列长度
状态转移: f ( i ) = m a x ( f [ j ] ) + 1 , j ∈ [ i − k , i + k ] f(i) = max(f[j]) + 1, j\in[i-k,i+k] f(i)=max(f[j])+1,j∈[i−k,i+k]
Code
class Solution {
public:
int longestIdealString(string s, int k) {
vector<int> dp(26);
for (int i = 0; i < int(s.size()); i++) {
int now = s[i] - 'a';
int mx = 0;
for (int j = now - k; j <= now + k && j <= 25; j++)
if (j >= 0)
mx = max(mx, dp[j]);
dp[now] = mx + 1;
}
return *max_element(dp.begin(), dp.begin() + 26);
}
};