Sunday 7 November 2021

Leetcode 118.Pascal's Triangle

 Problem Link: Click

This is a simple pascal triangle problem. One matter we have to keep in mind is we may have resize the vector size and allocate them carefully. Hence we have to return the vector.

Code:


class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int> > vec(numRows);
        for(int i=0;i<numRows;i++){
            vec[i].resize(i+1);
            vec[i][0]=1;
            vec[i][i]=1;
        }
        for(int i=2;i<numRows;i++){
            for(int j=1;j<i;j++){
                vec[i][j]=vec[i-1][j]+vec[i-1][j-1];
            }
        }
        return vec;
    }
};

Leetcode 73. Set Matrix Zeroes

 Problem link:click

This is very easy problem. In this problem you have to make all elements of a row or a column to zero if any element of the matrix of the specific row or column is zero. For this purpose we can take the first row and the first column as a flag of the row and column. If any element of a row or column is zero we will make the flag of first row and columns as zero.

For making all elements of the row and column zero we just have to check if matrix[i][0]==0 or matrix[0][j]==0.

Code:

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int col=matrix[0].size(),row=matrix.size(),col0=1;
        for(int i=0;i<row;i++){
            if(matrix[i][0]==0)col0=0;
            for(int j=1;j<col;j++){
                if(matrix[i][j]==0){
                    matrix[0][j]=0;
                    matrix[i][0]=0;
                }
            }
        }
        for(int i=row-1;i>=0;i--){
            for(int j=col-1;j>=1;j--){
                if(matrix[i][0]==0 || matrix[0][j]==0){
                    matrix[i][j]=0;
                }
            }
            if(col0==0)matrix[i][0]=0;
        }
    }
};

Monkey Banana Problem lightoj 1004

  In this problem we will check which adjacent cell will benefits the monkey best. For this, we will check all possible solution of this pro...