(Leetcode)backtracking回溯法 题目汇总

回溯法 Backtracking

Backtracking比较形象来说可以用走迷宫做例子,大多人类一般就是使用回溯法,当走到一条死路,就往回退到前一个岔路,尝试另外一条,直到走出。

简介
中文称做「回溯法」,穷举多维度数据的方法,可以想作是多维度的「穷举搜索」(Exhaustive Search)。
大意是:把多维度数据看做是是一个多维向量(solution vector),然后运用递回依序递回穷举各个维度的值,制作出所有可能的数据(solution space),并且在递回途中避免列举出不正确的数据。

多维数据搜索示意图

特点
Backtracking的好处,是在递回过程中,能有效的避免列举出不正确的数据,省下很多时间。
另外还可以调整维度的顺序、每个维度中列举值的顺序。如果安排得宜,可以更快的找到数据。

Leetcode 回溯法题目汇总

Tip:只汇总了博主做过的且想的起来的题,可能会继续更新。。

39. Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.

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

[
[7],
[2, 2, 3]
]

Java Code

public class Solution {
   
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> combination = new ArrayList<List<Integer>>();
        List<Integer> singleCombination = new ArrayList<Integer>();
        Arrays.sort(candidates);
        bac
### LeetCode 上的回溯算法练习题 #### N皇后问题 N皇后问题是经典的回溯算法应用之一。该问题的目标是在 n×n 的国际象棋棋盘上放置 n 个皇后,使得它们互相之间不能攻击对方。具体实现中,递归函数 `backtracking` 的作用是在棋盘上逐行放置皇后,并检查每一步是否符合规则[^1]。 ```cpp void backtracking(int n, int row, vector<string>& chessboard) { if (row == n) { // 所有皇后都成功放置的情况 result.push_back(chessboard); return; } for (int col = 0; col < n; ++col) { if (isValid(row, col, chessboard)) { chessboard[row][col] = 'Q'; // 放置皇后 backtracking(n, row + 1, chessboard); // 进入下一行放皇后 chessboard[row][col] = '.'; // 回溯,撤销当前格子上的皇后 } } } ``` 此代码片段展示了如何利用回溯法解决 N 皇后问题的核心逻辑。 #### 子集 II 去重 对于含有重复元素的数据集合,在求解其所有不重复子集时可以采用特定策略去除冗余项。当面对已排序数组中的重复情况时,可以通过记录前一访问过的元素来进行过滤操作[^2]。 ```cpp if (i > start && nums[i] == nums[i - 1]) continue; ``` 上述 C++ 片段用于跳过相同元素以避免生成重复组合。 #### 复原 IP 地址 另一个有趣的例子是从给定字符串构建有效的 IPv4 地址列表的任务。这同样依赖于回溯技术来探索所有潜在分割方案并验证合法性[^3]。 ```python def restoreIpAddresses(s: str): res = [] path = [] def backtrack(start=0): if len(path) == 4 and start == len(s): res.append('.'.join(path)) return for length in range(1, min(len(s)-start+1, 4)): part = s[start:start+length] if not isValidPart(part): break path.append(part) backtrack(start + length) path.pop() backtrack() return res ``` 这段 Python 实现了寻找所有可能的有效 IP 地址的过程。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值