# LeetCode算法代码笔记（36-40）

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

## 36. Valid Sudoku

sudoku

``````    '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

blank sudoku

filled_sudoku

``````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

``````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<List<Integer>> cs = new ArrayList<>();

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

public void sum(int[] candidates, int target, List<Integer> list, int index) {
for (int i = index; i < candidates.length; i++) {
List<Integer> temp = new ArrayList<>(list);
if (target == candidates[i]) {
continue;
} else if (candidates[i] > target) {
sum(candidates, target, temp, i + 1);
break;
} else if (target > 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]
]
``````

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

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Map<Integer, Integer> 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<Integer> list, Map<Integer, Integer> map) {
Set<Integer> keys = map.keySet();
Map<Integer, Integer> tempMap = new HashMap<>(map);
for (int key : keys) {
List<Integer> temp = new ArrayList<>(list);
int value = tempMap.get(key);
if (target == key) {
tempMap.remove(key);
continue;
} else if (key > target) {
tempMap.remove(key);
sum(target, temp, tempMap);
break;
} else if (target > key) {
if (value > 1) {
tempMap.put(key, tempMap.get(key) - 1);
} else {
tempMap.remove(key);
}
sum(target - key, temp, tempMap);
tempMap.remove(key);
}
}
}
}
``````

### 推荐阅读更多精彩内容

• 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪：刷leetcod...
土汪阅读 11,306评论 0 33
• leetcode刷题记录本文记录一下leetcode刷题记录，记录一下自己的解法和心得。 LeetCode Two...
EarthChen阅读 1,896评论 0 6
• 最近我在观察一些老人，由此来反观自己。我发现，人终其一生，一定要多一些爱好，一定要自知，最好能够有终身学习的意识。...
陳湘阅读 602评论 0 0
• 昨天装个sqlsever费了半天劲,今天想起来记下 sqlsever版本需要搭配服务器系统,之前装的是win200...
琴匣自鸣阅读 91评论 0 0
• 清明时节，有不羁的风徐徐吹向这胡同 清晨安安静静的石板路上铺满了落叶 远方传来秋雁凄迷呢哝的声音 秀才听闻马不停蹄...
努力练成文案妖阅读 134评论 0 0