给定一个非负整数数组 A,如果该数组每对相邻元素之和是一个完全平方数,则称这一数组为正方形数组。
返回 A 的正方形排列的数目。两个排列 A1 和 A2 不同的充要条件是存在某个索引 i,使得 A1[i] != A2[i]。
示例 1:
输入:[1,17,8]
输出:2
解释:
[1,8,17] 和 [17,8,1] 都是有效的排列。
示例 2:
输入:[2,2,2]
输出:1
提示:
1 <= A.length <= 12
0 <= A[i] <= 1e9
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:
1 <= A.length <= 12
0 <= A[i] <= 1e9
题意理解:根据 相邻两点和能直接平方,进行排序。本质是通过和为能开平方,进行 深度递归,进行排序。 也是一种 图,建立环图。
题目本质:找出关系判断的方式,for+dfs,找出所有可能的组合 方式,跟顺序也有关系。
同时注意细节,相邻的两个重复值算为1次,这个的判别方式,可用前面的也可用后面的;先排序,可用把重复 的情况归拢。记录路径,防止重复 ;注意回溯清除记录的数据。
应用:根据不同的关系方式,将 点串成环。
问题:重复的判别消除方式,退出dfs的条件,回溯法消除数据。防止数据错误修改。
package com.jd.jr.nlp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* for 遍历,保证可以取到所有值
* dfs 保证 可以从任一点开始遍历 dfs+for 可以 任意顺序的组合数字
* for dfs 之后,清空保存记录,可以在dfs完成 之后 不影响后续的操作
*
*/
public class Solution996Diy {
private int count=0;
private boolean isSquare(int a,int b){
double sqrt=Math.sqrt(a+b);
return (sqrt-Math.floor(sqrt))==0;
}
private int dfs(int[] A,List<Integer> temp,boolean[] hasVisited,int lastNumber){
for(int i=0;i<A.length;i++){
if(temp.size()==A.length){
this.count++;
return 0;
}
if(hasVisited[i]||(i>0 && !hasVisited[i-1] && A[i]==A[i-1] ) ){
continue;
}
if( (this.isSquare(A[i],lastNumber) || temp.size()==0)){
hasVisited[i]=true;
temp.add(A[i]);
this.dfs(A,temp,hasVisited,A[i]);
hasVisited[i]=false;
temp.remove(temp.size()-1);
}
}
return this.count;
}
public int numSquarefulPerms(int[] A) {
List<Integer> temp=new ArrayList<>();
boolean[] hasVisited=new boolean[A.length];
int lastNumber=-1;
Arrays.fill(hasVisited,false);
Arrays.sort(A);
this.dfs(A,temp,hasVisited,lastNumber);
return this.count;
}
public static void main(String[] args){
// boolean res = (sqr - Math.floor(sqr)) == 0;
// double a=Math.sqrt(4);
// System.out.println(a);
// System.out.println(Math.floor(5));
// System.out.println((Math.floor(5.1)-5)==0);
// List<Integer> nums=new ArrayList<>();
// nums.add(1);
// nums.add(2);
// nums.add(3);
// System.out.println(nums.toString());
// nums.remove(-1);
// System.out.println(nums.toString());
// 1 17 8 2 2 2
int[] A=new int[]{1,17,8};
// A=new int[]{2,2,2};
// A=new int[]{1,1,8,1,8};
Solution996Diy solution996Diy=new Solution996Diy();
int result=solution996Diy.numSquarefulPerms(A);
System.out.println("=========");
System.out.println(result);
}
}