2021/04/15
类似不带重复元素的全排列,加上一个剪枝就可以了。
impl Solution {
pub fn count_arrangement(n: i32) -> i32 {
let mut nums: Vec<_> = (1..=n).collect();
let mut vis: Vec<_> = (0..n).map(|x| false).collect();
let mut result = vec![];
Solution::count_arrangement_0(&mut nums, 0, &mut vis, &mut vec![], &mut result);
return result.len() as i32;
}
pub fn count_arrangement_0(arr: &mut Vec<i32>, idx: usize, vis: &mut Vec<bool>, collector: &mut Vec<i32>, res: &mut Vec<Vec<i32>>) {
if collector.len() == arr.len() {
res.push(collector.clone());
return;
}
for i in 0..arr.len() {
if vis[i] {
continue;
}
if !(arr[i] % (collector.len() + 1) as i32 == 0 || (collector.len() + 1) as i32 % arr[i] == 0) {
continue;
}
collector.push(arr[i]);
vis[i] = true;
Solution::count_arrangement_0(arr, idx + 1, vis, collector, res);
collector.pop();
vis[i] = false;
}
}
}