| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.PalindromePartitioning; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class PalindromePartitioningBackTracking : IPalindromePartitioning |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n * 2^n) |
| | 19 | | /// Space complexity - O(n * 2^n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="s"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public IList<IList<string>> Partition(string s) |
| 2 | 24 | | { |
| 2 | 25 | | IList<IList<string>> result = new List<IList<string>>(); |
| | 26 | |
|
| 2 | 27 | | Backtrack(s, 0, new List<string>(), result); |
| | 28 | |
|
| 2 | 29 | | return result; |
| 2 | 30 | | } |
| | 31 | |
|
| | 32 | | private static void Backtrack(string s, int start, IList<string> currentPartition, |
| | 33 | | ICollection<IList<string>> result) |
| 8 | 34 | | { |
| 8 | 35 | | if (start >= s.Length) |
| 3 | 36 | | { |
| 3 | 37 | | result.Add(new List<string>(currentPartition)); |
| | 38 | |
|
| 3 | 39 | | return; |
| | 40 | | } |
| | 41 | |
|
| 26 | 42 | | for (var end = start; end < s.Length; end++) |
| 8 | 43 | | { |
| 8 | 44 | | if (!IsPalindrome(s, start, end)) |
| 2 | 45 | | { |
| 2 | 46 | | continue; |
| | 47 | | } |
| | 48 | |
|
| 6 | 49 | | currentPartition.Add(s.Substring(start, end - start + 1)); |
| | 50 | |
|
| 6 | 51 | | Backtrack(s, end + 1, currentPartition, result); |
| | 52 | |
|
| 6 | 53 | | currentPartition.RemoveAt(currentPartition.Count - 1); |
| 6 | 54 | | } |
| 8 | 55 | | } |
| | 56 | |
|
| | 57 | | private static bool IsPalindrome(string s, int start, int end) |
| 8 | 58 | | { |
| 9 | 59 | | while (start < end) |
| 3 | 60 | | { |
| 3 | 61 | | if (s[start] != s[end]) |
| 2 | 62 | | { |
| 2 | 63 | | return false; |
| | 64 | | } |
| | 65 | |
|
| 1 | 66 | | start++; |
| 1 | 67 | | end--; |
| 1 | 68 | | } |
| | 69 | |
|
| 6 | 70 | | return true; |
| 8 | 71 | | } |
| | 72 | | } |