回溯算法

回溯算法

1、组合

力扣题目链接

给定两个整数 nk,返回范围 [1, n] 中所有可能的 k 个数的组合。

你可以按 任何顺序 返回答案。

示例 1:

1
2
3
4
5
6
7
8
9
10
输入:n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

示例 2:

1
2
输入:n = 1, k = 1
输出:[[1]]

提示:

  • 1 <= n <= 20
  • 1 <= k <= n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> current = new ArrayList<>();
backtrace(1,n,k,current,result);
return result;

}
public void backtrace (int start, int n, int k, List<Integer> current, List<List<Integer>>result) {
if(current.size() == k) {
result.add(new ArrayList<>(current));
return;
}
for (int i = start; i <= n; i++) {
current.add(i);
backtrace(i + 1, n, k, current, result);
current.remove(current.size()-1);
}
}
}

2、组合优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
List<List<Integer>> result = new LinkedList<>();
List<Integer> trace = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
track(n,1,k);
return result;
}
public void track (int n, int start, int k) {
if (trace.size() == k) {
result.add(new LinkedList(trace));
return;
}
for (int i = start ; i <= n-(k-trace.size())+1; i++) {
trace.add(i);
track(n,i+1,k);
trace.removeLast();
}
}
}

3. 组合总和III

https://leetcode.cn/problems/combination-sum-iii/description/

找出所有相加之和为 nk 个数的组合,且满足下列条件:

  • 只使用数字1到9
  • 每个数字 最多使用一次

返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。

示例 1:

1
2
3
4
5
输入: k = 3, n = 7
输出: [[1,2,4]]
解释:
1 + 2 + 4 = 7
没有其他符合的组合了。

示例 2:

1
2
3
4
5
6
7
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
解释:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
没有其他符合的组合了。

示例 3:

1
2
3
4
输入: k = 4, n = 1
输出: []
解释: 不存在有效的组合。
在[1,9]范围内使用4个不同的数字,我们可以得到的最小和是1+2+3+4 = 10,因为10 > 1,没有有效的组合。

提示:

  • 2 <= k <= 9
  • 1 <= n <= 60
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
class Solution {
List<List<Integer>> result = new LinkedList<>();
List<Integer> trace = new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backtrack(k,n,1,0);
return result;
}
public void backtrack (int k, int n, int start, int sum) {
if (trace.size()==k) {
if (sum == n) {
result.add(new LinkedList(trace));
}
return;
}
if (sum > n) {
return;
}
for (int i = start; i <= 9-(k-trace.size())+1; i++) {
sum += i;
trace.add(i);
backtrack(k,n,i+1,sum);
sum -= i;
trace.removeLast();
}
}
}

4. 电话号码的字母组合

https://leetcode.cn/problems/letter-combinations-of-a-phone-number/description/

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

img

示例 1:

1
2
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

示例 2:

1
2
输入:digits = ""
输出:[]

示例 3:

1
2
输入:digits = "2"
输出:["a","b","c"]

提示:

  • 0 <= digits.length <= 4
  • digits[i] 是范围 ['2', '9'] 的一个数字。
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
class Solution {
List<String> result = new LinkedList<>();
String[] numString = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
StringBuilder sb = new StringBuilder();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length()==0) {
return result;
}
backTracking (digits,0);
return result;
}
void backTracking(String digits, int index) {
if (index == digits.length()) {
result.add(sb.toString());
return;
}
int digit = digits.charAt(index) - '0';
String str = numString[digit];
for (int i = 0; i < str.length(); i++) {
sb.append(str.charAt(i));
backTracking(digits,index+1);
sb.deleteCharAt(sb.length()-1);
}
}
}

5.组合总和

https://leetcode.cn/problems/combination-sum/description/

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

1
2
3
4
5
6
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:

1
2
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

1
2
输入: candidates = [2], target = 1
输出: []

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
List<List<Integer>> result = new LinkedList<>();
List<Integer> trace = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backTracing(candidates,target,0,0);
return result;
}
void backTracing (int [] candidates, int target, int sum, int startIndex) {
if (sum == target) {
result.add(new LinkedList(trace));
return;
}
if (sum > target) {
return;
}
for (int i = startIndex; i < candidates.length; i++) {
sum += candidates[i];
trace.add(candidates[i]);
backTracing(candidates,target,sum,i);
sum -= trace.get(trace.size()-1);
trace.removeLast();
}
}
}

6.组合总和II

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次

注意:解集不能包含重复的组合。

示例 1:

1
2
3
4
5
6
7
8
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

示例 2:

1
2
3
4
5
6
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]

提示:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30
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
class Solution {
List<List<Integer>> result = new LinkedList<>();
LinkedList<Integer> trace = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backTracing(candidates, target, 0, 0);
return result;
}
void backTracing (int[] candidates, int target, int sum, int startIndex) {
if (sum == target) {
result.add(new LinkedList(trace));
return;
}
if (sum > target) {
return;
}
for (int i = startIndex; i < candidates.length; i++) {
if (i > startIndex && candidates[i] == candidates[i-1]) {
continue;
}
trace.add(candidates[i]);
sum += candidates[i];
backTracing(candidates, target, sum, i+1);
sum -= trace.get(trace.size()-1);
trace.removeLast();
}
}
}

6. 分割回文串

https://leetcode.cn/problems/palindrome-partitioning/

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是

回文串

。返回 s 所有可能的分割方案。

示例 1:

1
2
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

示例 2:

1
2
输入:s = "a"
输出:[["a"]]

提示:

  • 1 <= s.length <= 16
  • s 仅由小写英文字母组成
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
class Solution {
List<List<String>> result = new LinkedList<>();
List<String> trace = new LinkedList<>();
public List<List<String>> partition(String s) {
backTracking(s,0);
return result;
}
void backTracking(String s, int startIndex) {
if (startIndex == s.length()) {
result.add(new LinkedList(trace));
return;
}
for (int i = startIndex; i < s.length(); i++) {
String sb = s.substring(startIndex,i+1);
if(isPalindrome(sb)) {
trace.add(sb);
backTracking(s,i+1);
trace.removeLast();
}
}
}
boolean isPalindrome (String s) {
for (int i = 0, j = s.length()-1; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}

7.复原IP地址

https://leetcode.cn/problems/restore-ip-addresses/description/

有效 IP 地址 正好由四个整数(每个整数位于 0255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。

  • 例如:"0.1.2.201" "192.168.1.1"有效 IP 地址,但是 "0.011.255.245""192.168.1.312""192.168@1.1"无效 IP 地址。

给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 '.' 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。

示例 1:

1
2
输入:s = "25525511135"
输出:["255.255.11.135","255.255.111.35"]

示例 2:

1
2
输入:s = "0000"
输出:["0.0.0.0"]

示例 3:

1
2
输入:s = "101023"
输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

提示:

  • 1 <= s.length <= 20
  • s 仅由数字组成
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
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
List<String> result = new LinkedList<>();
public List<String> restoreIpAddresses(String s) {
backTracking(s,0,0);
return result;
}
void backTracking(String s, int startIndex, int pointSum) {
if (pointSum == 3) {
if (isVaild(s,startIndex,s.length()-1)) {
result.add(s);
return;
}
}
for (int i = startIndex ; i < s.length(); i++) {
if (isVaild(s,startIndex,i)){
s = s.substring(0,i+1) + '.' + s.substring(i+1);
pointSum++;
backTracking(s,i+2,pointSum);
pointSum--;
s = s.substring(0,i+1) + s.substring(i+2);
}
}
}
boolean isVaild (String s, int start, int end) {
// 1. 每个整数都在0-255之间
// 2. 不还有特殊字符
// 3. 首位不为0
if (start > end) {
return false;
}
if ((end-start) >= 1 && s.charAt(start) == '0') {
return false;
}
int num = 0;
for (int i = start; i <= end; i++) {
int temp = s.charAt(i) - '0';
if ( temp > 9 || temp < 0 ) {
return false;
}
num = 10*num + temp;
}
if ( num > 255 || num < 0 ) {
return false;
}
return true;
}

}

8.子集问题

https://leetcode.cn/problems/subsets/

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的

子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例 1:

1
2
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

示例 2:

1
2
输入:nums = [0]
输出:[[],[0]]

提示:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • nums 中的所有元素 互不相同
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> trace = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
backTracking(nums,0);
return result;
}
void backTracking (int[] nums, int startIndex) {
if (startIndex > nums.length) return;
result.add(new ArrayList(trace));
for (int i = startIndex; i < nums.length; i++) {
trace.add(nums[i]);
backTracking(nums,i+1);
trace.removeLast();
}
}
}

9.子集II

https://leetcode.cn/problems/subsets-ii/description/

给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的

子集(幂集)。

解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。

示例 1:

1
2
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]

示例 2:

1
2
输入:nums = [0]
输出:[[],[0]]

提示:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
Arrays.sort(nums);
dfs(nums, 0, path, result);
return result;
}
void dfs(int[] nums, int start, List<Integer> path, List<List<Integer>> result) {
result.add(new ArrayList<>(path));
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i-1]) {
continue;
}
path.add(nums[i]);
dfs(nums, i+1, path, result);
path.remove(path.size()-1);
}
}
}
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
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

class Solution {
private List<List<Integer>> result;
private List<Integer> path;

public List<List<Integer>> subsetsWithDup(int[] nums) {
result = new ArrayList<>();
path = new ArrayList<>();
Arrays.sort(nums);
backTracking(nums, 0);
return result;
}

private void backTracking(int[] nums, int start) {
result.add(new ArrayList<>(path));
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i - 1]) {
continue;
}
path.add(nums[i]);
backTracking(nums, i + 1);
path.remove(path.size() - 1);
}
}
}

10、递增子序列

https://programmercarl.com/0491.%E9%80%92%E5%A2%9E%E5%AD%90%E5%BA%8F%E5%88%97.html

给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。

数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。

示例 1:

1
2
输入:nums = [4,6,7,7]
输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]

示例 2:

1
2
输入:nums = [4,4,3,2,1]
输出:[[4,4]]

提示:

  • 1 <= nums.length <= 15
  • -100 <= nums[i] <= 100
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
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> trace = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backTracking(nums, 0);
return result;
}
void backTracking(int[] nums, int stratIndex) {
if(stratIndex > nums.length) {
return;
}
if (trace.size()>=2) {
result.add(new ArrayList(trace));
}
Set<Integer> used = new HashSet<>();
for (int i = stratIndex; i < nums.length; i++) {
if (!trace.isEmpty() && nums[i] < trace.get(trace.size()-1)) {
continue;
}
if (used.contains(nums[i])) {
continue;
}
trace.add(nums[i]);
used.add(nums[i]);
backTracking(nums,i+1);
trace.remove(trace.size()-1);
}
}
}

11、全排列

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例 1:

1
2
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

示例 2:

1
2
输入:nums = [0,1]
输出:[[0,1],[1,0]]

示例 3:

1
2
输入:nums = [1]
输出:[[1]]

提示:

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • nums 中的所有整数 互不相同
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
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> trace = new ArrayList<>();
boolean[] used;
public List<List<Integer>> permute(int[] nums) {
used = new boolean [nums.length];
backTracking(nums);
return result;
}
void backTracking(int[] nums) {
if (trace.size() == nums.length) {
result.add(new ArrayList(trace));
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue;
}
trace.add(nums[i]);
used[i] = true;
backTracking(nums);
used[i] = false;
trace.remove(trace.size()-1);
}
}
}

12、全排列II

给定一个可包含重复数字的序列 nums按任意顺序 返回所有不重复的全排列。

示例 1:

1
2
3
4
5
输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]

示例 2:

1
2
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

提示:

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10
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
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> trace = new ArrayList<>();
boolean [] used;
public List<List<Integer>> permuteUnique(int[] nums) {
used = new boolean [nums.length];
backTracking(nums);
return result;
}
void backTracking (int[] nums) {
if(trace.size() == nums.length){
result.add(new ArrayList(trace));
return;
}
Set<Integer> appear = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if(used[i] || appear.contains(nums[i])) {
continue;
}
appear.add(nums[i]);
used[i] = true;
trace.add(nums[i]);
backTracking(nums);
used[i] = false;
trace.remove(trace.size()-1);
}
}
}

13、重新安排行程

给你一份航线列表 tickets ,其中 tickets[i] = [fromi, toi] 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。

所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。如果存在多种有效的行程,请你按字典排序返回最小的行程组合。

  • 例如,行程 ["JFK", "LGA"]["JFK", "LGB"] 相比就更小,排序更靠前。

假定所有机票至少存在一种合理的行程。且所有的机票 必须都用一次 且 只能用一次。

示例 1:

img

1
2
输入:tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
输出:["JFK","MUC","LHR","SFO","SJC"]

示例 2:

img

1
2
3
输入:tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
输出:["JFK","ATL","JFK","SFO","ATL","SFO"]
解释:另一种有效的行程是 ["JFK","SFO","ATL","JFK","ATL","SFO"] ,但是它字典排序更大更靠后。

提示:

  • 1 <= tickets.length <= 300
  • tickets[i].length == 2
  • fromi.length == 3
  • toi.length == 3
  • fromitoi 由大写英文字母组成
  • fromi != toi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public List<String> findItinerary(List<List<String>> tickets) {
Map<String, PriorityQueue<String>> graph = new HashMap();
for (List<String> ticket : tickets) {
graph.putIfAbsent(ticket.get(0),new PriorityQueue<String>());
graph.get(ticket.get(0)).offer(ticket.get(1));
}
List<String> result = new LinkedList<>();
dfs ("JFK",graph,result);
return result;

}
void dfs (String head, Map<String, PriorityQueue<String>> graph, List<String> result) {
while (graph.containsKey(head) && !graph.get(head).isEmpty()){
String next = graph.get(head).poll();
dfs(next,graph,result);
}
result.addFirst(head);
}
}

PriorityQueue 是一种特殊的队列,它按照优先级来处理队列中的元素,而不是按照元素被插入队列的顺序。在 PriorityQueue 中,元素的优先级决定了它们的出队顺序。通常,优先级高的元素会先被处理。它在许多算法和数据结构中都有应用,尤其是在需要按优先级进行调度、排序、合并等操作的场景中。

Java 中的 PriorityQueue

在 Java 中,PriorityQueue 是一个实现了 Queue 接口的类,它提供了一个基于堆(通常是最小堆)实现的队列。它会按照元素的自然顺序或通过传递的 Comparator 来决定优先级。

主要特点:

  1. 最小堆(Min-Heap)
    • 默认情况下,PriorityQueue 使用自然顺序(元素的比较方法,如数字的大小或字符串的字典顺序),这意味着队列中最小的元素会先被移除。
    • 可以通过传入 Comparator 来改变优先级的顺序,使用最大堆(Max-Heap)或自定义顺序。
  2. 无界队列
    • PriorityQueue 默认没有容量限制,元素数量只受可用内存的限制。
  3. 线程不安全
    • PriorityQueue 不是线程安全的,如果多个线程并发操作同一个队列,需要使用外部同步机制,或者使用 PriorityBlockingQueue 来替代。

基本操作:

  • add(E e) / offer(E e):向队列添加元素。
  • remove() / poll():移除并返回队列中优先级最高的元素(对于最小堆,就是最小的元素)。
  • peek():返回队列中优先级最高的元素,但不移除它。
  • size():返回队列中元素的数量。
  • clear():清空队列中的所有元素。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
```



#### 14、N皇后

按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子。

**n 皇后问题** 研究的是如何将 `n` 个皇后放置在 `n×n` 的棋盘上,并且使皇后彼此之间不能相互攻击。

给你一个整数 `n` ,返回所有不同的 **n 皇后问题** 的解决方案。

每一种解法包含一个不同的 **n 皇后问题** 的棋子放置方案,该方案中 `'Q'` 和 `'.'` 分别代表了皇后和空位。



**示例 1:**

![img](https://assets.leetcode.com/uploads/2020/11/13/queens.jpg)

输入:n = 4
输出:[[“.Q..”,”…Q”,”Q…”,”..Q.”],[“..Q.”,”Q…”,”…Q”,”.Q..”]]
解释:如上图所示,4 皇后问题存在两个不同的解法。

1
2
3

**示例 2:**

输入:n = 1
输出:[[“Q”]]

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

**提示:**

- `1 <= n <= 9`

```java
class Solution {
List<List<String>> result = new ArrayList<>();
public List<List<String>> solveNQueens(int n) {
char[][] chessboard = new char[n][n];
for (char[]c : chessboard) {
Arrays.fill(c,'.');
}
backTracking(chessboard,n,0);
return result;
}
void backTracking(char[][] chessboard,int n, int row){
if (row == n) {
result.add(ArrayToList(chessboard));
return;
}
for (int i = 0; i < n; i++) {
if (isVaild(chessboard,n,row,i)){
chessboard[row][i] = 'Q';
backTracking(chessboard,n,row+1);
chessboard[row][i] = '.';
}
}
}
List<String> ArrayToList(char[][]chessboard) {
List<String> list = new ArrayList<>();
for (char[]c : chessboard) {
list.add(String.copyValueOf(c));
}
return list;
}
boolean isVaild (char[][] chessboard, int n, int row, int column) {
// 检查同一列列是否有Q
for(int i = 0; i <= row; i++) {
if(chessboard[i][column] == 'Q') {
return false;
}
}
// 检查45度斜线
for (int i = row -1, j = column - 1; i>=0&&j>=0; i--,j--) {
if(chessboard[i][j] == 'Q') {
return false;
}
}
// 检查135度
for (int i = row -1, j = column + 1; i>=0&&j<n; i--,j++) {
if(chessboard[i][j] == 'Q') {
return false;
}
}
return true;
}
}

15、解数独

编写一个程序,通过填充空格来解决数独问题。

数独的解法需 遵循如下规则

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)

数独部分空格内已填入了数字,空白格用 '.' 表示。

示例 1:

img

1
2
3
输入:board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
输出:[["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
解释:输入的数独如上图所示,唯一有效的解决方案如下所示:

提示:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] 是一位数字或者 '.'
  • 题目数据 保证 输入数独仅有一个解
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
37
38
39
40
41
42
43
44
45
46
class Solution {
public void solveSudoku(char[][] board) {
backTracking (board);
}
boolean backTracking(char[][] board) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
continue;
}
for (char k = '1'; k <= '9'; k++) {
if (isVaild(board,i,j,k)){
board[i][j] = k;
if (backTracking(board)){
return true;
}
board[i][j] = '.';
}
}
return false;
}
}
return true;
}
boolean isVaild(char[][]board, int row, int column, char k){
for (int i = 0; i < 9; i++) {
if (board[row][i] == k) {
return false;
}
}
for (int i = 0; i < 9; i++) {
if(board[i][column] == k) {
return false;
}
}

for (int i = (row/3)*3; i < (row/3)*3+3; i++) {
for (int j = (column/3)*3; j<(column/3)*3+3;j++) {
if(board[i][j]==k) {
return false;
}
}
}
return true;
}
}
作者

John Doe

发布于

2024-09-04

更新于

2025-02-28

许可协议

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.
You need to set client_id and slot_id to show this AD unit. Please set it in _config.yml.