Posts

Saturday, September 9th

Image
 Combination Sums Given an array of integers and a target value, return the number of combinations that can add up to the target I first approached the problem using brute force, but then with a timeout on values of {1, 2, 3} and a target of 40, pivoted to dynamic programming This idea behind the dynamic programming approach here is like the earlier DP problem of moving right and down along a grid towards a finish square.  In that type of problem, the total number of ways to reach a square equals the number of ways to reach the square above, plus the number of ways to reach the square to the left. In this case, the number of ways to reach a target value equals the number of ways to reach a target value minus the values in nums.  This forms the meat of the program, the recurrence relation in a top down approach:      int ans= 0 ; int num; for ( int i= 0 ; i< nums . size (); i++) { num= nums [i]; ans+= dp (val-num); } The re...

Friday, September 8th

Image
Pascal's triangle Given an integer n , return the first n  rows of Pascal's triangle   I was able to solve this in 2 different ways: iterative and recursive For the iterative, we begin by declaring the answer vector and setting the base case when numrows =1. vector < vector < int >> generate ( int numRows ) { vector<vector< int > > ans; vector< int > one; one . push_back ( 1 ); ans . push_back (one); if (numRows== 1 ) return ans;          ... } Beyond that, we iterate through rows 1 at a time, calculating new values from the previous row.  For each row beyond row 1 (indexed at 0), we get the previous row, then create a new row and push 1 to the front.        for ( int i = 1 ; i < numRows ; i ++ ) { vector < int > row , prevrow ; row . push_back ( 1 ) ; prevrow = ans [ i - 1 ] ;       ...