【Leetcode】Perfect Squares

来源:互联网 发布:蜂窝数据打开自动关闭 编辑:程序博客网 时间:2024/06/04 01:29

题目链接:https://leetcode.com/problems/perfect-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 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

思路:

 n=m^2+s
 m=(int)Math.sqrt(n) 向下取整 表最大可能的完全平方数 c[i]表示组成i需要的最少完全平方数的个数 递推公式:

c[i] =1+c[s] 考虑12=3^2+3 c[12]=1+c[3]=1+3=4, 但12=4+4+4 即c[12]=3
所以不是m为最大的平方数就一定能取得c[i]的,需要遍历 所有j<m n=j^2+k min(1+c[k])

算法:

public int numSquares(int n) {      int c[] = new int[n + 1];      for (int i = 1; i <= n; i++) {          int tmp = (int) Math.sqrt(i);          c[i] = c[i - tmp * tmp] + 1;          for (int j = tmp - 1; j >= 1; j--) {              tmp = j * j;              c[i] = Math.min(c[i - tmp] + 1, c[i]);          }      }      return c[n];  }  


2 0
原创粉丝点击