# 131.Palindrome-Partitioning

## 131. Palindrome Partitioning

## 题目地址

<https://leetcode.com/problems/palindrome-partitioning/>

## 题目描述

```
Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]
```

## 代码

### Approach 1: Backtracing

```java
public class Solution {
    public List<List<String>> partition(String s) {
    List<List<String>> result = new ArrayList<List<String>>();
    if (s == null || s.isEmpty()) return result;

    List<String> palindromes = new ArrayList<String>();
    dfs(s, 0, palindromes, result);

    return result;
  }

  private void dfs(String s, int pos, List<String> palindromes, List<List<String>> ret) {
    if (pos == s.length()) {
      ret.add(new ArrayList<String>(palindromes));
      return;
    }

    for (int i = pos + 1; i <= s.length(); i++) {
      String substr = s.substring(pos, i);
      if (!isPalindrome(sbustr)) {
        continue;
      }

      palindromes.add(substr);
      dfs(s, i, palindromes, ret);
      palindromes.remove(palindromes.size() - 1);
    }
  }

  private boolean isPalindrome(String s) {
    if (s == null || s.isEmpty()) return false;

    int n = s.length();
    for (int i = 0; i < n; i++) {
      if (s.charAt(i) != s.charAt(n - i - 1)) return false;
    }

    return true;
  }

}
```


---

# 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://wentao-shao.gitbook.io/leetcode/graph-search/131.palindrome-partitioning.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.
