Leetcode:279Perfect Squares

来源:互联网 发布:简单的sql注入 编辑:程序博客网 时间:2024/05/16 15:57

 题目出处:Leetcode:279Perfect Squares

题目描述:

Given a positive integer n, find the least number of perfect square numbers (for example,1, 4, 9, 16, ...) which sum to n.

For example, given n = 12, return 3 because12 = 4 + 4 + 4; given n = 13, return 2 because13 = 4 + 9.


翻译很简单,此处不再赘述。

这是一个dp问题(动态规划问题)动态公式:dp[i + j * j] = min(dp[i] + 1,dp[i + j * j ]);

已通过系统的代码:

public class Solution {    public int numSquares(int n) {        int[] squ = new int[n + 1];        for(int i = 1;i*i <=n ; i++)            squ[i*i] = 1;        for(int j = 1,k = 1; j + k * k <= n;j++){            for(;j + k * k <= n;k++){                if((squ[j + k * k] == 0)||squ[j+k*k]>(squ[j]+1))                    squ[j + k * k] = squ[j] + 1;            }            k = 1;        }        return squ[n];    }}



0 0
原创粉丝点击