日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

996. Number of Squareful Arrays

發布時間:2023/12/10 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。