虽然自己面试已经挂了,但是还是做了一下笔试。前面4题没啥难度的,最后一题是个区间DP。
#include <iostream> #include <vector> using namespace std; int n; vector<int> num; void slove() { int n = num.size(); vector<vector<int>> left (n, vector<int>(n, 0)); //向左归并 vector<vector<int>> right(n, vector<int>(n, 0)); //向右归并 for (int len = 2; len <= n; len++) { for (int i = 0; i + len - 1 < n; i++) { int j = i + len - 1; int tmp_left = num[i], tmp_right = num[j]; left[i][j] = min(left[i + 1][j] + abs(tmp_left - num[i + 1]), right[i + 1][j] + abs(tmp_left - num[j])); right[i][j] = min(right[i][j-1] + abs(tmp_right - num[j-1]), left[i][j-1] + abs(tmp_right - num[i])); } } cout << min(left[0][n - 1], right[0][n - 1]) << endl; } int main() { int t; cin >> n; while (n--) { cin >> t; num.push_back(t); } slove(); return 0; }
第四题:
//k=str.size()-n; k代表需要删除字母的个数 //解题思路 贪心 string slove(string str, int k) { if (str.size() <= k) return ""; string res; int count = 0; for (int i = 0; i < str.size(); i++) { if (res.size() == 0) res += str[i]; else if (res.back() < str[i] && count < k) { while (res.back() < str[i] && count < k) { count++; res.pop_back(); } res += str[i]; } else res += str[i]; } while (count < k) res.pop_back(),count++; return res; }
全部评论
(3) 回帖