Skip to content

Commit e8191d6

Browse files
committed
double DP
1 parent 71000fa commit e8191d6

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

Palindrome Partitioning II ,cpp.h

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
//state: F[i] from 0 - i position the # of minimum cut
3+
//function: f[i] = min(f[j] + 1 j < i && s[i , j] is palindrome)
4+
// initialization: f[0] = 0
5+
// answer: f[s.size()]
6+
//here is another problem, check a string is palindrome is also time-comsuming
7+
// so we will use another DP to solve that
8+
// s[i][j] = s[i-1][j-1] i < j && s[i] == s[j]
9+
// this problem turns out to be a double DP problem
10+
class Solution {
11+
public:
12+
int minCut(string s) {
13+
const int n = s.size();
14+
int f[n + 1];
15+
bool p[n][n];
16+
fill_n(&p[0][0], n * n, false);
17+
for(int i = 0; i <= n; i++){
18+
f[i] = n - 1 - i; // worst case each char is a cut
19+
}
20+
for(int i = n - 1; i >= 0; i--){
21+
for(int j = i; j < n; j++){
22+
if(s[i] == s[j] && (j -i < 2 ||p[i+1][j-1])){
23+
p[i][j] = true;
24+
f[i] = min(f[i], f[j+1] + 1);
25+
}
26+
}
27+
}
28+
return f[0];
29+
30+
}
31+
32+
};

Roman to Integer.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,5 @@ class Solution {
2727
}
2828
return result;
2929
}
30-
};
30+
};
31+

0 commit comments

Comments
 (0)