Sunday, March 26, 2017

#codingexercise
Count the number of distinct subsequences
Void  Combine(ref List<int> A, ref List<int> b, int start, int level, ref List<List<int>> sequences) 
for (int I =start; I < A.length; I++) 
 
   if (b.contains(A[i])== false){ 
     b[level] = A[i]; 
     sequences.Add(b); 
  if (I < A.length) 
    Combine(ref A, ref b, m, start+1, level+1, ref sequences); 
  b[level] = '/0'; 
}
}
return sequences.Distinct();
Alternatively,
int GetCountDistinct(List<int> A)
{
    var digits = new int[10];
     digits.ForEach(x => x = -1);
    int n = A.Count;
    int dp[n+1];
    dp[0] = 1;
    for (int i=1; i<=n; i++)
    {
        dp[i] = 2*dp[i-1];
        if (digits[A[i-1]] != -1)
            dp[i] = dp[i] - dp[digits[A[i-1]]];
        digits[A[i-1]] = (i-1);
    }
    return dp[n];
}

No comments:

Post a Comment