Uncategorized

Combinations [LC # 77]





Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
 Example: 

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
class Solution {
    public List<List<Integer>> combine(int n, int k) {
        
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> current = new ArrayList<>();
        
        dfs(result, current, n, k, 1);
        
        return result;
        
    }
    
    private void dfs(List<List<Integer>> result, 
                     List<Integer> current, 
                     int n, int k, int pos){
        
        if(current.size() == k){
            result.add(new ArrayList<>(current));
            return;
        }
        
        if(pos > n) return;
        
        for(int i = pos; i <= n; i++){
            current.add(i);
            dfs(result, current, n, k, i + 1);
            current.remove(current.size() - 1);
        }
    }
        
}

You never change your life until you step out of your comfort zone; change begins at the end of your comfort zone

Depth First Search · DFS · Graphs · leetcode

Number Of Islands

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

Continue reading “Number Of Islands”