leetcode 279. Perfect Squares【dp】

来源:互联网 发布:狗带什么意思网络语言 编辑:程序博客网 时间:2024/05/18 00:25

279. Perfect Squares

Description Submission Solutions
  • Total Accepted: 66852
  • Total Submissions: 188029
  • Difficulty: Medium
  • Contributors: Admin

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 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.

Show Tags
Show Similar Problems


public class Solution{  public int numSquares(int n){  int[] dp=new int[n+1];  Arrays.fill(dp,Integer.MAX_VALUE);  for(int i=0;i*i<=n;i++)    dp[i*i]=1;  for(int a=0;a<=n;a++){    for(int b=0;a+b*b<=n;b++){        dp[a+b*b]=Math.min(dp[a]+1,dp[a+b*b]);    }  }return dp[n];  }}


0 0
原创粉丝点击