Day 28 of LeetCode

Photo by Warren Umoh on Unsplash

Day 28 of LeetCode

ยท

2 min read

Documenting LeetCode solving.

Q85

51. N-Queens

Hard.

class Solution {

    List<List<String>> res = new ArrayList<>();
    // To check whether can put to the postion or not.
    // Same column
    Set<Integer> col = new HashSet<>();
    // Same positive diagnal
    Set<Integer> posDiag = new HashSet<>();
    // Same negative diagnal
    Set<Integer> negDiag = new HashSet<>();

    List<String> board = new ArrayList<>();

    public List<List<String>> solveNQueens(int n) {
        // Initialize board
        // e.g. ["....", "....", "....", "...."]
        for (int i = 0; i < n; i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < n; j++) {
                sb.append(".");
            }
            board.add(sb.toString());
        }

        backtrack(0, n);
        return res;
    }

    public void backtrack(int r, int n) {
        if (r == n) {
            res.add(new ArrayList<>(board));
            return;
        }

        for (int c = 0; c < n; c++) {
            if (col.contains(c) || posDiag.contains(r + c) || negDiag.contains(r - c)) {
                continue;
            }

            col.add(c);
            posDiag.add(r + c);
            negDiag.add(r - c);
            StringBuilder sb = new StringBuilder(board.get(r));
            sb.setCharAt(c, 'Q');
            board.set(r, sb.toString());

            backtrack(r + 1, n);

            col.remove(c);
            posDiag.remove(r + c);
            negDiag.remove(r - c);
            sb.setCharAt(c, '.');
            board.set(r, sb.toString());

        }
    }
}

Q86

70. Climbing Stairs

Easy. 1D DP.

Neetcode, youtube.com/watch?v=Y0lT9Fck7qI

class Solution {
    public int climbStairs(int n) {
        int one, two;
        one = two = 1;

        for (int i = 0; i < n - 1; i++) {
            int temp = one;
            one = one + two;
            two = temp;
        }

        return one;
    }
}

Q87

746. Min Cost Climbing Stairs

Easy. 1D DP.

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int n = cost.length;
        // I used a very weird way to construct the dp array lol
        int[] dp = new int[n + 1];
        dp[n] = 0;
        dp[n - 1] = cost[n - 1];

        for (int i = n - 2; i >= 0; i--) {
            dp[i] = cost[i] + Math.min(dp[i + 1], dp[i + 2]);
        }

        return Math.min(dp[0], dp[1]);

    }
}

Did you find this article valuable?

Support ๐Ÿฐ Evelyn's Learning Journey by becoming a sponsor. Any amount is appreciated!

ย