25 line recursive solution in java


  • 2
    C
    public class Solution {
        List<List<String>> res = new ArrayList<List<String>>();
        List<String> cur = new ArrayList<String>();
        public List<List<String>> partition(String s) {
            backTracking(s, 0);
            return res;
        }
        
        private void backTracking(String s, int start){
            if(start == s.length()){
                res.add(new ArrayList<String>(cur));
                return;
            } 
            for(int i = start; i < s.length(); i++){
                if(isPalindrome(s.substring(start, i+1))){
                    cur.add(s.substring(start, i+1));
                    backTracking(s, i+1);
                    cur.remove(cur.size()-1);
                }
            }
        }
        
        private boolean isPalindrome(String s){
            return new StringBuffer(s).reverse().toString().equals(s);
        }
    }

  • 0
    S
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.