996. Number of Squareful Arrays

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!)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值