LeetCode算法代码笔记(36-40)

给自己的目标:[LeetCode](https://leetcode.com/ "Online Judge Platform") 上每日一题

在做题的过程中记录下解题的思路或者重要的代码碎片以便后来翻阅。
项目源码:github上的Leetcode

36. Valid Sudoku

题目:给出九个字符串,每个字符串有数字和 '.'组成,'.'表示要填写的数字,判断这九个字符串能否组成一个有效的数独。
有效数独:每个单元,每行,每列都必须有1-9组成,不能重复。不一定要求有解。

LeetCode算法代码笔记(36-40)_第1张图片
sudoku

不要傻乎乎的循环去求每行每列和每个单元是否存在重复数字,可以给每个数字进行位置标记,再利用set看是否有重复。

    '4' in row 7 is encoded as "(4)7".
    '4' in column 7 is encoded as "7(4)".
    '4' in the top-right block is encoded as "0(4)2".
public class Solution {

    public boolean isValidSudoku(char[][] board) {
        Set seen = new HashSet();
        for (int i = 0; i < 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (board[i][j] != '.') {
                    String b = "(" + board[i][j] + ")";
                    if (!seen.add(b + i) || !seen.add(j + b) || !seen.add(i / 3 + b + j / 3))
                        return false;
                }
            }
        }
        return true;
    }

}

37. Sudoku Solver

题目:给出一个有效的数独表,求空缺值。假设必定有解。

LeetCode算法代码笔记(36-40)_第2张图片
blank sudoku

LeetCode算法代码笔记(36-40)_第3张图片
filled_sudoku

使用回溯来求解,每个空格可以填1-9的值,每填入一个值去判断数独表是否是有效的数独表,若有效填写下一个无效则循环0-9,循环结束后没有找到值则回到上一个。

public class Solution {
    public void solveSudoku(char[][] board) {
        sudoku(board, 0,0);
    }

    public boolean sudoku(char[][] board, int i, int j) {
        if (j >= 9) {
            return sudoku(board, i + 1, 0);
        }
        if (i >= 9) {
            return true;
        }
        char c = board[i][j];
        if (c != '.') {
            return sudoku(board, i, j + 1);
        } else {
            for (int k = 1; k <= 9; k++) {
                char cc = (char) (k + '0');
                board[i][j] = cc;
                if (isValidSudoku(i, j, board)) {
                    if (sudoku(board, i, j + 1)) {
                        return true;
                    }
                }
                board[i][j] = '.';
            }
        }
        return false;
    }

    public boolean isValidSudoku(int i, int j, char[][] board) {
        for (int k = 0; k < 9; k++) {
            if (k != j && board[i][k] == board[i][j])
                return false;
        }
        for (int k = 0; k < 9; k++) {
            if (k != i && board[k][j] == board[i][j])
                return false;
        }
        for (int row = i / 3 * 3; row < i / 3 * 3 + 3; row++) {
            for (int col = j / 3 * 3; col < j / 3 * 3 + 3; col++) {
                if ((row != i || col != j) && board[row][col] == board[i][j])
                    return false;
            }
        }
        return true;
    }
}

38. Count and Say

题目:n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。依次类推,写个countAndSay(n)函数返回字符串。

1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

这道题理解了题意就是一道简单题,代码如下:

public class Solution {
    public String countAndSay(int n) {
        String result = "1";
        if (n <= 1) {
            return result;
        }
        for (int i = 1; i < n; i++) {
            StringBuilder res = new StringBuilder();
            int count = 1;
            char c = result.charAt(0);
            for (int j = 1; j < result.length(); j++) {
                if (c == result.charAt(j)) {
                    count++;
                } else {
                    res.append(count).append(c);
                    count = 1;
                    c = result.charAt(j);
                }
            }
            res.append(count).append(c);
            result = res.toString();
        }
        return result;
    }
}

39. Combination Sum

题目:给出一组数字和一个目标数,数组内部的数字不重复,但可以多次使用。求数组里面和为目标数的组合。要求组合不能重复。

For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
  [7],
  [2, 2, 3]
]

递归求解。
1)当目标值与当前所选择的值相等时,将组合加入列表时。
2)当目标值大于所选择的值时,将值加入组合并将目标值减去选择值进入下一轮递归。
3)当目标值小于所选择的值,跳过当前值。

public class Solution {
    List> cs = new ArrayList<>();

    public List> combinationSum(int[] candidates, int target) {
        sum(candidates, target, new ArrayList<>(), 0);
        return cs;
    }

    public void sum(int[] candidates, int target, List list, int index) {
        for (int i = index; i < candidates.length; i++) {
            List temp = new ArrayList<>(list);
            if (target == candidates[i]) {
                temp.add(candidates[i]);
                cs.add(temp);
                continue;
            } else if (candidates[i] > target) {
                sum(candidates, target, temp, i + 1);
                break;
            } else if (target > candidates[i]) {
                temp.add(candidates[i]);
                sum(candidates, target - candidates[i], temp, i);
            }

        }
    }
}

40. Combination Sum II

题目:给出一组数字和一个目标数,数组内部的数字有重复,且只能使用一次。求数组里面和为目标数的组合。要求组合不能重复

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

我使用的方法是使用map来去重和记录数字重复的个数,虽然也能AC但map的寻址拖慢了整个运行速度。最优的解法是先对数组进行排序,当遇到重复的数字时跳过重复的步骤。

/**
* 有待优化的代码
*/
public class Solution {
    List> cs = new ArrayList<>();

    public List> combinationSum2(int[] candidates, int target) {
        Map map = new HashMap<>();
        for (int i = 0; i < candidates.length; i++) {
            map.put(candidates[i], map.getOrDefault(candidates[i], 0) + 1);
        }
        sum(target, new ArrayList<>(), map);
        return cs;
    }

    public void sum(int target, List list, Map map) {
        Set keys = map.keySet();
        Map tempMap = new HashMap<>(map);
        for (int key : keys) {
            List temp = new ArrayList<>(list);
            int value = tempMap.get(key);
            if (target == key) {
                temp.add(key);
                cs.add(temp);
                tempMap.remove(key);
                continue;
            } else if (key > target) {
                tempMap.remove(key);
                sum(target, temp, tempMap);
                break;
            } else if (target > key) {
                temp.add(key);
                if (value > 1) {
                    tempMap.put(key, tempMap.get(key) - 1);
                } else {
                    tempMap.remove(key);
                }
                sum(target - key, temp, tempMap);
                tempMap.remove(key);
            }
        }
    }
}

你可能感兴趣的:(LeetCode算法代码笔记(36-40))