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"] ]
1 public class Solution { 2 public IList<IList<string>> Partition(string s) { 3 var results = new List<IList<string>>(); 4 5 DFS(s, 0, new List<string>(), results); 6 7 return results; 8 } 9 10 private void DFS(string s, int start, IList<string> result, IList<IList<string>> results) 11 { 12 if (start >= s.Length) 13 { 14 results.Add(new List<string>(result)); 15 return; 16 } 17 18 for (int i = start; i < s.Length; i++) 19 { 20 var ss = s.Substring(start, i - start + 1); 21 22 if (IsPalindrome(ss)) 23 { 24 result.Add(ss); 25 26 DFS(s, i + 1, result, results); 27 28 result.RemoveAt(result.Count - 1); 29 } 30 } 31 } 32 33 private bool IsPalindrome(string s) 34 { 35 if (s.Length <= 1) return true; 36 37 int i = 0, j = s.Length - 1; 38 while (i < j) 39 { 40 if (s[i] != s[j]) return false; 41 i++; 42 j--; 43 } 44 45 return true; 46 } 47 }