原题说明
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful.  Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input:
[1,17,8]
Output:2
Explanation:[1,8,17]and[17,8,1]are the valid permutations.
Example 2:
Input:
[2,2,2]
Output:1
Note:
解题思路
经典的backtracking回溯算法:
用一个vector<int> cur记录当前的permutation, 用vector<bool> used记录第i个元素是否被选如当前的permutation中。
遍历过程中要判断重复元素的情况,因此需要先排序将重复的元素排在一起,每一轮遍历都只选择重复元素中第一个出现的。
示例代码 (cpp)
| 1 | class Solution { | 
复杂度分析
时间复杂度: O(N!) 因为一共有N!种可能的排列组合,每一种都会遍历一遍
空间复杂度: O(N * N!) = O(N!)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!
