文章目录
- 1 题目理解
- 2 回溯分析
1 题目理解
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].
这道题目英文不好,还真不好理解。看力扣的官方翻译。
给定一个非负整数数组 A,如果该数组每对相邻元素之和是一个完全平方数,则称这一数组为正方形数组。
返回 A 的正方形排列的数目。两个排列 A1 和 A2 不同的充要条件是存在某个索引 i,使得 A1[i] != A2[i]。
输入:非负整数数组A
输出:A的正方形排列的数目,应该是A的正方形数组的排列数目。
规则:正方形数组是该数组中每对相邻元素之和是一个完全平方数。另外要注意就是数组不能重复。
例如:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
2 回溯分析
首先要返回的是排列数,应该可以套用排列的模块。其次,数组元素有重复,需要去重,选择题目47的模块。
我们套用模板,可以得到数组A所有的排列,那这个排列是否满足要求呢?在生成排列过程中检查一下相邻元素是否为完全平方数即可。
class Solution {private int count;private boolean[] visited;private int[] nums;public int numSquarefulPerms(int[] A) {if(A==null || A.length==0) return 0;count = 0;Arrays.sort(A);this.nums = A;visited = new boolean[nums.length];dfs(0,new ArrayList<Integer>());return count;}private void dfs(int index,List<Integer> list){if(index == this.nums.length){count++;return;}for(int i = 0;i<nums.length;i++){if(!visited[i]){if(list.isEmpty() || isSquare(list.get(list.size()-1),nums[i])){visited[i] = true;list.add(nums[i]);dfs(index+1,list);visited[i]=false;list.remove(list.size()-1);}while(i+1<nums.length && nums[i+1]==nums[i]) i++;}}}private boolean isSquare(int a, int b){int sum = a+b;int x = (int)Math.sqrt(sum);return x*x == sum;}
}
这是做得最简单的一道hard题目。
时间复杂度O(n!)O(n!)O(n!)