# Longest Palindromic Subsequence

> Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.

## Thoughts

数组找长度想DP。刚开始还想是不是用背包做，发现做不出来。实际上沿着回文一般解法即可，让f\[j]\[i]表示从j到i最长回文长度，对每个j, i判断是否相等，相等意味着保留ij能构成新的回文，旧长度+2。不等则意味着j和i不能共存, 可以是从j到i-1最长回文长度或者j + 1到i的。

## Code

```
class Solution {
    public int longestPalindromeSubseq(String s) {
        int n = s.length();
        int[][] f = new int[n][n];


        for (int i = 0; i < n; i++) {
            f[i][i] = 1;
            for (int j = i - 1; j >= 0; j--) {
                if (s.charAt(i) == s.charAt(j)) {
                    f[j][i] = f[j + 1][i - 1] + 2;
                } else {
                    f[j][i] = Math.max(f[j][i - 1], f[j + 1][i]);
                }
            }
        }


        return f[0][n - 1];
    }
}
```

## Analysis

时间复杂度为O(n^2).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hao-fu-1.gitbook.io/oj/dynamic_programming_i/palindromic/longest-palindromic-subsequence.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
