Leetcode 279 Perfect Squares

每条边距离为1的Dij,求从n到0的距离

class Solution {
    public int numSquares(int n) {
        PriorityQueue<Pair<Integer,Integer>> q = 
                new PriorityQueue<Pair<Integer,Integer>>((a,b) -> a.getValue() - b.getValue());
        int []dp = new int[n+1];
        dp[n] = 0;
        for(int i=0;i<n;i++)
            dp[i] = 0x3f3f3f;
        q.offer(new Pair(n,0));
        while(!q.isEmpty()){
            int a = q.peek().getKey();
            int b = q.poll().getValue();
            if(dp[a]<b)
                continue;
            dp[a] = b;
            if(a==0) return b;
            for(int i=1;i<=Math.sqrt(a);i++){
                if(dp[a-i*i]>dp[a]+1){
                    dp[a-i*i] = dp[a]+1; 
                    q.offer(new Pair(a-i*i,dp[a]+1));
                }
            }
        }
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/Dale_zero/article/details/120413133