File tree Expand file tree Collapse file tree 3 files changed +61
-0
lines changed Expand file tree Collapse file tree 3 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 1
1
// ============================================================================
2
+ // Palindrome Partitioning
2
3
// Given a string s, partition s such that every substring of the partition
3
4
// is a palindrome.
4
5
//
16
17
#include < iostream>
17
18
#include < vector>
18
19
#include < queue>
20
+
19
21
using namespace std ;
20
22
21
23
class Solution {
Original file line number Diff line number Diff line change
1
+ // ============================================================================
2
+ // Palindrome Partitioning II
3
+ // Given a string s, partition s such that every substring of the partition
4
+ // is a palindrome.
5
+ //
6
+ // Return the minimum cuts needed for a palindrome partitioning of s.
7
+ //
8
+ // For example, given s = "aab",
9
+ // Return 1 since the palindrome partitioning ["aa","b"] could be produced
10
+ // using 1 cut.
11
+ //
12
+ // ============================================================================
13
+
14
+ #include < iostream>
15
+ #include < vector>
16
+ #include < queue>
17
+
18
+ using namespace std ;
19
+
20
+ class Solution {
21
+ public:
22
+ int minCut (string s)
23
+ {
24
+ if (s.empty ()) return 0 ;
25
+ int N = s.size ();
26
+
27
+ vector<vector<bool > > dp1 (N, vector<bool >(N, false ));
28
+ for (int i = N-1 ; i >= 0 ; i--)
29
+ for (int j = i; j < N; j++)
30
+ if (i == j)
31
+ dp1[i][j] = true ;
32
+ else if (i + 1 == j)
33
+ dp1[i][j] = (s[i] == s[j]);
34
+ else
35
+ dp1[i][j] = (s[i] == s[j] && dp1[i+1 ][j-1 ]);
36
+
37
+ vector<int > dp2 (N+1 , 0 );
38
+ dp2[0 ] = -1 ;
39
+ for (int i = 2 ; i <= N; i++)
40
+ {
41
+ dp2[i] = dp2[i-1 ] + 1 ;
42
+ for (int j = i-2 ; j >= 0 ; j--)
43
+ if (dp1[j][i-1 ])
44
+ dp2[i] = min (dp2[i], 1 + dp2[j]);
45
+ }
46
+
47
+ return dp2[N];
48
+ }
49
+ };
50
+
51
+ int main ()
52
+ {
53
+ Solution sol;
54
+ auto res = sol.minCut (" abbab" );
55
+ cout << res << endl;
56
+ }
Original file line number Diff line number Diff line change @@ -61,6 +61,8 @@ NextPermutation
61
61
N-Queens
62
62
N-QueensII
63
63
PalindromeNumber
64
+ PalindromePartitioning
65
+ PalindromePartitioningII
64
66
PartitionList
65
67
PascalTriangle
66
68
PascalTriangleII
@@ -108,6 +110,7 @@ SubsetsII
108
110
SubstringwithConcatenationofAllWords
109
111
SudokuSolver
110
112
SumRoottoLeafNumbers
113
+ SurroundedRegions
111
114
SwapNodesinPairs
112
115
SymmetricTree
113
116
TextJustification
You can’t perform that action at this time.
0 commit comments