From 85fcd9e620169d700f704dfa395327535de9541b Mon Sep 17 00:00:00 2001 From: Eatswap Date: Fri, 14 Apr 2023 17:47:13 +0800 Subject: [PATCH] add: 230414 --- cpp/2304/230414.cpp | 46 +++++++++++++++++++++++++++++++++++++++++ cpp/2304/CMakeLists.txt | 2 +- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 cpp/2304/230414.cpp diff --git a/cpp/2304/230414.cpp b/cpp/2304/230414.cpp new file mode 100644 index 0000000..2e74c1b --- /dev/null +++ b/cpp/2304/230414.cpp @@ -0,0 +1,46 @@ +#include +#include +#include + +/** + * 516. Longest Palindromic Subsequence + * + * Given a string s, find the longest palindromic subsequence's length in s. + * A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. + */ + +class Solution { +private: + std::string s; + int ans[1001][1001]{}; + + int dp(int, int); + +public: + int longestPalindromeSubseq(std::string); +}; + +int Solution::longestPalindromeSubseq(std::string str) { + this->s = std::move(str); + return dp(0, s.size() - 1); +} + +int Solution::dp(int x, int y) { + int& a = ans[x][y]; + if (a) + return a; + if (x == y) + return a = 1; + if (1 == y - x) + return a = 1 + (s[x] == s[y]); + return a = std::max( + (s[x] == s[y]) * 2 + dp(x + 1, y - 1), + std::max(dp(x + 1, y), dp(x, y - 1)) + ); +} + +int main() { + auto* s = new Solution; + std::cout << s->longestPalindromeSubseq("cbbd"); + return 0; +} diff --git a/cpp/2304/CMakeLists.txt b/cpp/2304/CMakeLists.txt index 7400f38..918cef6 100644 --- a/cpp/2304/CMakeLists.txt +++ b/cpp/2304/CMakeLists.txt @@ -4,4 +4,4 @@ PROJECT(2304) SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_EXPORT_COMPILE_COMMANDS true) -ADD_EXECUTABLE(2304 230414-CN.cpp) +ADD_EXECUTABLE(2304 230414.cpp)