Monday, May 12, 2014

Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1

Solution :

We first find the digit starting from unit's place that is less than the preceding digit. In an Array A start with i = n-2. compare A[n-2] with A[n-1] and keep decrementing i till we find A[i]
For eg: in 1,3,2 we get i=0;
In another example 1,2,4,3,1,1 we get i =1. Hence the value 0 to i-1 need not be disturbed. We now need to find the next permutation of number starting from i.
We now need to find the next digit which is the least digit greater than A[i].
For that we move from the end of array and stop at k=3 (A[k]=3). We now swap A[i] and A[k]. So the array now is 1,3,4,2,1,1. Now we reverse the array starting from i+1. We now get 1,3,1,1,2,4 which is the next permutation.



Code: 

Saturday, May 10, 2014

Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.

Solution : 

This can be done by in place dynamic programming. The idea is to replace matrix[i][j] values with the minimum value that can be achieved (among two paths) to reach matrix[i][j].
We can reach matrix[i][j] through one of 
matrix[i-1][j] or
matrix[i][j-1]
We record the minimum of these two at matrix[i][j].

Code:
class Solution {
public:
    int minPathSum(vector > &grid) {

    int i,j;
     for(i=0;i
        for(j=0;j
        {
           if(!(i==0 && j==0))
            {
                if(i==0 && j>0)
                  grid[i][j] += grid[i][j-1];
              else  if(i> && j==0)
                 grid[i][j]  += grid[i-1][j];
               else
                 grid[i][j] += min(grid[i][j-1], grid[i-1][j]); 
             }
         }
         return grid[i][j];
}
};