题目链接:526. 优美的排列
树型结构:
预处理 matchmatchmatch 数组(每个位置符合条件的数有哪些):
void getMatch(int n) {used.resize(n + 1);match.resize(n + 1);for (int i = 1; i <= n; i++) {for (int j = 1; j <= n; j++) {if (i % j == 0 || j % i == 0) {match[i].push_back(j);}}}}
(1) 回溯函数参数及返回值:
indexindexindex 记录遍历到第几个数字, 表示递归的深度。
usedusedused 数组记录排列里哪些元素已经被使用了,一个排列里一个元素只能使用一次。
matchmatchmatch 二维数组用来存放不同的集合(每个位置符合条件的数有哪些),每个 indexindexindex 对应一个集合。
resresres 表示符合条件的集合的个数。
vector used;vector> match;int res;void backtracking(int n, int index) {
(2) 终止条件:
由树型结构可知,当 index==n+1index == n + 1index==n+1, 收集结果并返回。
if (index == n + 1) {res++;return;}
(3) 确定单层递归逻辑:
首先要取 indexindexindex 对应的 matchmatchmatch 里面的数字,然后 forforfor 循环来处理这个集合。
一个排列里的一个元素只能使用一次,所以当该元素已经被使用,直接 continuecontinuecontinue。
注意递归参数要 index+1index + 1index+1, 因为下一层要处理下一个数字了。
for (auto& x : match[index]) {if (used[x] == true) {continue;}used[x] = true;backtracking(n, index + 1);used[x] = false;}
代码如下:
class Solution {
private:vector used;vector> match;int res;void backtracking(int n, int index) {if (index == n + 1) {res++;return;}for (auto& x : match[index]) {if (used[x] == true) {continue;}used[x] = true;backtracking(n, index + 1);used[x] = false;}}void getMatch(int n) {used.resize(n + 1);match.resize(n + 1);for (int i = 1; i <= n; i++) {for (int j = 1; j <= n; j++) {if (i % j == 0 || j % i == 0) {match[i].push_back(j);}}}}
public:int countArrangement(int n) {getMatch(n);backtracking(n, 1);return res;}
};