其实试探回溯法,最经典的考题是N皇后问题。国际象棋中皇后的势力范围覆盖其所在的水平线上,垂直线,以及两条对角线。N皇后问题就是:在n*n的棋盘上放置n个皇后,如何使得她们彼此互不攻击,此时称她们构成一个可行的棋局。
但是这个问题我真的还没有找到答案,即使在discussion里面有代码。所以我们先来看看一道“简单的”leetcode(tag: backtracing,number:216):
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
题目给了你一个target number(n),k代表了你可以在1到9里面选k个数字,1到9的数字里面每个数字只能用一次,相加求和得到target
number,然后返回所有可能的集合,下面展示了leetcode 的AC代码:
class Solution {
public:
void combination(vector<vector<int>>& result, vector<int> sol, int k, int n) {
if (sol.size() == k && n == 0) { result.push_back(sol); return ; }
if (sol.size() < k) {
for (int i = sol.empty() ? 1 : sol.back() + 1; i <= 9; ++i) {
if (n - i < 0) break;
sol.push_back(i);
combination(result, sol, k, n - i);
sol.pop_back();
}
}
}
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> result;
vector<int> sol;
combination(result, sol, k, n);
return result;
}
};
刚刚接触回溯法,可能感觉递归特别变扭。但是当你把整个recursion trace 画下来,思路就会清晰很多。很多大神可能觉得特别low,但是不积跬步无以至千里:
这个递归跟踪图里面只完成了一个可能组合的分析,每个调用实例都用一个方框表示,然后break跳出函数用红线表示,return回上一级调用用红色虚线表示。
leetcode: 40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
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]
]
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> sol;
int n=0;
sort(candidates.begin(),candidates.end());
combination(res,sol,candidates,target,n);
return res;
}
void combination(vector<vector<int>> &res, vector<int> sol,vector<int> candidates, int target,int n){
if(target==0) {
res.push_back(sol);
return;
}
for(auto i=n;i!=candidates.size();++i)
{
if(target-candidates[i]<0) break;
if(i&&candidates[i]==candidates[i-1]&&i>n) continue;
sol.push_back(candidates[i]);
combination(res,sol,candidates,target-candidates[i],i+1);
sol.pop_back();
}
}
};
在这道题里面,我们先对向量进行排序,然后使用和前面那题很类似的递归算法,不过这里有一条核心语句,它保证了集合的唯一性:
if(i&&candidates[i]==candidates[i-1]&&i>n) continue;