0191-0200

191. Number of 1 Bits $\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  int hammingWeight(uint32_t n) {
    int ans;

    for (ans = 0; n != 0; ++ans) n &= n - 1;

    return ans;
  }
};

192. Word Frequency $\star\star$

193. Valid Phone Numbers $\star$

194. Transpose File $\star\star$

195. Tenth Line $\star$

196. Delete Duplicate Emails $\star$

197. Rising Temperature $\star$

198. House Robber $\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int rob(vector<int>& nums) {
    int dp1 = 0;
    int dp2 = 0;

    for (int num : nums) {
      int temp = dp1;
      dp1 = max(dp1, dp2 + num);
      dp2 = temp;
    }

    return dp1;
  }
};

199. Binary Tree Right Side View $\star\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  vector<int> rightSideView(TreeNode* root) {
    vector<int> ans;

    dfs(root, 1, ans);

    return ans;
  }

 private:
  void dfs(TreeNode* root, int level, vector<int>& ans) {
    if (!root) return;
    if (level > ans.size()) ans.push_back(root->val);

    dfs(root->right, level + 1, ans);
    dfs(root->left, level + 1, ans);
  }
};

200. Number of Islands $\star\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
 public:
  int numIslands(vector<vector<char>>& grid) {
    if (grid.empty()) return 0;

    const int m = grid.size();
    const int n = grid[0].size();

    int ans = 0;
    vector<vector<bool>> visited(m, vector<bool>(n));

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (!visited[i][j] && grid[i][j] == '1') {
          ++ans;
          dfs(grid, i, j, visited);
        }

    return ans;
  }

 private:
  void dfs(vector<vector<char>>& grid, int i, int j,
           vector<vector<bool>>& visited) {
    if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size() ||
        visited[i][j] || grid[i][j] == '0')
      return;

    visited[i][j] = true;

    dfs(grid, i + 1, j, visited);
    dfs(grid, i - 1, j, visited);
    dfs(grid, i, j + 1, visited);
    dfs(grid, i, j - 1, visited);
  }
};