There is an O(n 2 ) dynamic programming algorithm for counting the number of palindromic subsequences of a string; you can use this to count the number of non-palindromic subsequences by subtracting the number of palindromic subsequences from the number of subsequences (which is just 2 n ).
This algorithm counts subsequences by criterion in the OP; two subsequences are considered different if there is a difference in the list of indices used to select the elements, even if the resulting subsequences have the same elements.
To count the palindromic subsequences, we create an account based on the intervals of the sequence. In particular, we define:
S i,j = substring S starting at index i and ending at index j (inclusive)
P i,j = number of palindromic subsequences S i,j
Now each singleton interval is a palindrome, therefore:
P i,i = 1 P i,i = 1 for all i < n
If the substring does not start and does not end with the same element (i.e., S i β S j ), then palindromic subsequences consist of:
Those that contain S i but do not contain S j
Those that contain S j but do not contain S i
Those that contain neither S i nor S j
Now notice that P i,j-1 contains both the first and third set of subsequences, and P i+1,j includes both the second and third set; P i+1,j-1 is exactly the third set. Hence:
P i,j = P i+1,j + P i,j-1 β P i+1,j-1 P i,j = P i+1,j + P i,j-1 β P i+1,j-1 if S i β S j
But what if S i = S j S i = S j ? In this case, we must add palindromes consisting of S i , followed by the palindrome of the subsequence of S i+1,j-1 , followed by S j , as well as the palindrome subsequence, consisting only of the starting and ending characters. (Technically, an empty sequence is a palindrome, but we donβt count it here.) The number of subsequences that we add is P i + 1, j-1 & plus; 1, which cancels the deductible double count in the above equation. So:
P i,j = P i+1,j + P i,j-1 + 1 P i,j = P i+1,j + P i,j-1 + 1 if S i = S j S i = S j .
To save space, we can actually calculate P i,i+k for 0 β€ i < |S|-k to increase the values ββof k ; we need to save only two of these vectors to get the final result P 0, | S | -1 .
EDIT
Here is a small python program; the first calculates the number of palindromic subsequences, as described above, and the driver calculates the number of non-palindromic subsequences (i.e. the number of ways to remove zero or more elements and create a non-palindrome, if the original sequence is a palindrome, then this is the number of ways to remove one or more elements.)
# Count the palindromic subsequences of s def pcount(s): length = len(s) p0 = [0] * (length + 1) p1 = [1] * length for l in range(1, length): for i in range(length - l): p0[i] = p1[i] if s[i] == s[i + l]: p1[i] += p1[i+1] + 1 else: p1[i] += p1[i+1] - p0[i+1]