码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Perfect Squares

时间:2016-09-01 12:48:33      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

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.

Analysis:

A DP solution like the Coin Changes.

Solution:

 1 public class Solution {
 2     public int numSquares(int n) {
 3         int[] nums = new int[n+1];
 4 
 5         for (int i=1;i<=n;i++){
 6             nums[i] = Integer.MAX_VALUE;
 7             for (int j=1;j*j<=i;j++){
 8                 nums[i] = Math.min(nums[i], nums[i-j*j]+1);
 9             }
10         }
11         return nums[n];
12     }
13 }

 

LeetCode-Perfect Squares

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/5829322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!