七、最后一块石头的重量
class Solution {
public :
int lastStoneWeight ( vector< int > & stones) {
priority_queue< int > q;
for ( int s : stones) {
q. push ( s) ;
}
while ( q. size ( ) > 1 ) {
int a = q. top ( ) ;
q. pop ( ) ;
int b = q. top ( ) ;
q. pop ( ) ;
if ( a > b) {
q. push ( a - b) ;
}
}
return q. empty ( ) ? 0 : q. top ( ) ;
}
} ;
class Solution {
public :
int lastStoneWeightII ( vector< int > & stones) {
int sum = 0 ;
for ( auto x : stones)
sum += x;
int n = stones. size ( ) , m = sum / 2 ;
vector< vector< int >> dp ( n + 1 , vector < int > ( m + 1 ) ) ;
for ( int i = 1 ; i <= n; i++ ) {
for ( int j = 0 ; j <= m; j++ ) {
dp[ i] [ j] = dp[ i - 1 ] [ j] ;
if ( j >= stones[ i - 1 ] )
dp[ i] [ j] = max ( dp[ i] [ j] , dp[ i - 1 ] [ j - stones[ i - 1 ] ] +
stones[ i - 1 ] ) ;
}
}
return sum - 2 * dp[ n] [ m] ;
}
} ;
八、分割回文串
class Solution {
private :
vector< vector< int >> f;
vector< vector< string>> ans;
vector< string> path;
int n;
void dfs ( const string& s, int i) {
if ( i == n) {
ans. push_back ( path) ;
return ;
}
for ( int j = i; j < n; ++ j) {
if ( isPalindrome ( s, i, j) == 1 ) {
path. push_back ( s. substr ( i, j - i + 1 ) ) ;
dfs ( s, j + 1 ) ;
path. pop_back ( ) ;
}
}
}
int isPalindrome ( const string& s, int i, int j) {
if ( f[ i] [ j] != 0 )
return f[ i] [ j] ;
if ( i > j || i == j || ( i + 1 == j && s[ i] == s[ j] ) )
return f[ i] [ j] = 1 ;
f[ i] [ j] = ( s[ i] == s[ j] ? isPalindrome ( s, i + 1 , j - 1 ) : - 1 ) ;
return f[ i] [ j] ;
}
public :
vector< vector< string>> partition ( string s) {
n = s. size ( ) ;
f. assign ( n, vector < int > ( n) ) ;
dfs ( s, 0 ) ;
return ans;
}
} ;
class Solution
{
void init ( const string & s, vector< vector< bool >> & isPal)
{
int n = s. size ( ) ;
for ( int i = n - 1 ; i >= 0 ; i-- )
{
for ( in