You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
There are 5 ways to assign symbols to make the sum
of nums be target 3.
Note:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.
Solutions
My solutions
The longest palindrome subsequence of s is the longest common subsequence of s and the reverse of s.
Define dp[i + 1][j] to be the length of the longest common subsequence of s[0..i] and reverse(s[j..n-1]). It is easy to get the recursive relation.
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n + 1, vector<int>(n + 1));
for(int i = 0; i < n; ++i){
for(int j = n - 1; j >= 0; --j){
if(s[i] == s[j]){
dp[i + 1][j] = dp[i][j + 1] + 1;
}else{
dp[i + 1][j] = max(dp[i][j], dp[i + 1][j + 1]);
}
}
}
return dp[n][0];
}
};
Directly define dp[i][j] to be the longest palindrome subsequence of s[i..j].
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n));
for(int i = 0; i < n; ++i){
dp[i][i] = 1;
}
for(int step = 1; step < n; ++step){
for(int i = 0; i + step < n; ++i){
int j = i + step;
if(s[i] == s[j]){
dp[i][j] = dp[i + 1][j - 1] + 2;
}else{
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n-1];
}
};
More efficient implementations
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n));
for(int i = n - 1; i >= 0; --i){
dp[i][i] = 1;
for(int j = i + 1; j < n; ++j){
if(s[i] == s[j]){
dp[i][j] = dp[i + 1][j - 1] + 2;
}else{
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
};
O(n) space.
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<int> dp(n);
for(int i = n - 1; i >= 0; --i){
dp[i] = 1;
int prev_j = 0;
for(int j = i + 1; j < n; ++j){
int temp = dp[j];
if(s[i] == s[j]){
dp[j] = prev_j + 2;
}else{
dp[j] = max(dp[j], dp[j - 1]);
}
prev_j = temp;
}
}
return dp[n-1];
}
};