Description
Sort a linked list in time using constant space complexity.
Analysis
We can solve this problem with DP solution. Here we use to represent the number of sub-string appearing in string .
So if , then we know
and if ,
where indicates the number of matches where we use to match , while indicates the number of matches where we do not use to match .
As we can see, in the iteration, we only use information in iteration. Thus there is no need to save a 2D array, as all information in iterations is useless. One thing worth noting that in the second layer of loop, we need to loop from to , i.e. in the reverse order. The reason is that if we iterate from , will be overwritten by , then will be calculated using instead of , which is wrong.
Solution
1 class Solution {
2 public:
3 int numDistinct(string S, string T) {
4 int num[T.size()+1];
5 memset(num, 0, sizeof(int) * (T.size()+1));
6 num[0] = 1;
7 for (int i = 1; i <= S.size(); ++ i)
8 for (int j = T.size(); j >= 1; -- j) // attention here: reverse iteration
9 if (S[i-1] == T[j-1])
10 num[j] += num[j-1];
11
12 return num[T.size()];
13 }
14 };