996. Number of Squareful Arrays
文章目錄
- 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!)
總結
以上是生活随笔為你收集整理的996. Number of Squareful Arrays的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深入浅出 RPC - 浅出篇+深入篇
- 下一篇: Amesim学习——传热基础案例:烧红铁