Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

完全平方数 #17

Open
JesseZhao1990 opened this issue Jul 1, 2018 · 0 comments
Open

完全平方数 #17

JesseZhao1990 opened this issue Jul 1, 2018 · 0 comments

Comments

@JesseZhao1990
Copy link
Owner

JesseZhao1990 commented Jul 1, 2018

image

/**
 * @param {number} n
 * @return {number}
 */
function node(val,step){
    this.val = val;
    this.step = step;
}

var numSquares = function(n) {
    var queue = [];
    var visited = {};
    
    queue.push(new node(n,0));
    visited[n] = true;
    
    while(queue.length>0){
        var front = queue[0].val;
        var step = queue[0].step;
        queue.shift();
        
        if(front===0) return step;
        
        for(var i=0;front-i*i>=0;i++){
            if(visited[front-i*i]!== true){
                queue.push(new node(front-i*i,step+1));
                visited[front-i*i]= true;
            }
        }
    }
    
};

思路:建模,整个问题转化为图论问题
从N到0的所有节点,如果某两个节点之间相差一个完全平方数,则连接一条边。此时我们得到了一个无权图,成功将问题转化为求这个无权图中从N到0的最短路径问题。

leetcode原题地址:https://leetcode-cn.com/problems/perfect-squares/description/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant