题目

image.png

代码

  1. class Solution {
  2. List < List<String> > result = new ArrayList<>();
  3. Deque<String> deque = new LinkedList();
  4. public List<List<String>> partition(String s) {
  5. backtracking(s,0);
  6. return result;
  7. }
  8. public void backtracking(String s, int startIndex ) {
  9. if(startIndex == s.length() ) {
  10. result.add(new ArrayList(deque) );
  11. return ;
  12. }
  13. for(int i = startIndex; i < s.length(); i++ ) {
  14. if(isPandrome(s,startIndex,i) ) {
  15. deque.addLast(s.substring(startIndex, i+ 1) );
  16. backtracking(s,i + 1);
  17. deque.removeLast();
  18. } else {
  19. continue;
  20. }
  21. }
  22. }
  23. public boolean isPandrome(String s,int begin,int end ) {
  24. while(begin < end ) {
  25. if(s.charAt(begin++) != s.charAt(end--)) {
  26. return false;
  27. }
  28. }
  29. return true;
  30. }
  31. }