Nov 13, 2009

Known binary search tree and two values, find the number of nodes in the binary search tree, where the value of node is between two values

int foo(tree* node, int min, int max, int& count)
{
if(!root) return;
if(root->val>min && root->val < max)
{
count++;
foo(node->left,min,max,count);
foo(node->right,min,max,count);
}
else if(root->val>max) foo(node->left,min,max,count);
else if(root->val < min) foo(node->right,min,max,count);
}

Oct 18, 2009

The return value of the assignment operator is always *this instead of void, because assignment operator supports concatenation assignment like a=b=c

The return value of the assignment operator is always *this instead of void, because assignment operator supports concatenation assignment like a=b=c
http://en.wikipedia.org/wiki/Assignment_operator_in_C%2B%2B

Aug 11, 2009

Balance partition Input: give you a integer set {A[0]…A[n-1]}, 0 < A[i] < k, partition to two subsets S1 and S2, minimize |sum(S1)-sum(S2)|

Balance partition
Input: give you a integer set {A[0]…A[n-1]}, 0 < A[i] < k, partition to two subsets S1 and S2, minimize |sum(S1)-sum(S2)|
p(i,j)=1 means there is at least one subset in set i{A[0]…A[i-1]} has sum of j. i is from 0~n-1, j is from 0~(n-1)k
p(i,j)=0 means there is no subset in set i{A[0]…A[i-1]} has sum of j
so
p(i,j) =max{p(i-1,j),p(i-1,j-A[i])}
and define s=sum{A[0]…A[n-1]}/2
so minimize |sum(S1)-sum(S2)|= minimize |s-i:p(i,j)=1|

Longest increasing subsequence in array A[n]

Longest increasing subsequence in array A[n]
L(j)=max{L(i)}+1, where i < j and A[i] < A[j]
max_g=max{L(j)}
O(n^2)

int foo(int A[], int len)
{
int max_g=0;
int L[len];
for(int j=0;j < len;j++)
{
for(i=0; i < j; i++)
{
if(A[i] < A[j])
L[j]=max(L[j],L[i]+1);
}
max_g=max(max_g,L[j]);
}
return max_g;
}

Aug 5, 2009

Convert string to integer num, convert integer num to string

Convert string to integer num, convert integer num to string
1 A
2 B

27 AA
28 AB
int foo(char* str)
{
if(!str) return 0;
int num=0;
int len=strlen(str)-1;
int idx=len;
while(idx>=0)
{
num+=(str[idx]-'A'+1)*pow(26,len-idx);
idx--;
}
return num;
}
char* foo(int num)
{
if(num<=0) return NULL;
char* str=new char[11];
int idx=0;
while(num>=0)
{
str[idx]=num%26+'A'-1;
num/=26;
idx++;
}
str[idx]='\0';
return reverse(str);
}