首页 > 其他 > 详细

Perfect Squares

时间:2016-07-12 06:43:50      阅读:202      评论: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.

Example

Given n = 12, return 3 because 12 = 4 + 4 + 4
Given n = 13, return 2 because 13 = 4 + 9

分析:

首先把所有 1-n 的square numbers找出来。然后利用DP去求。Assume count[j] is the least number of perfect square numbers which sum to j.

count[j] = Math.min(count[j - list.get(k)] + 1, count[j])

Here list contains all the square numbers from 1 to n, and 1 <= list.get(k) <= j

 1 public class Solution {
 2     /**
 3      * @param n a positive integer
 4      * @return an integer
 5      */
 6     public int numSquares(int n) {
 7         ArrayList<Integer> list = new ArrayList<Integer>();
 8         int i = 1;
 9         while (i * i <= n) {
10             list.add(i * i);
11             i++;
12         }
13         int[] count = new int[n + 1];
14         count[0] = 0;
15         
16         for (int j = 1; j <= n; j++) {
17             count[j] = Integer.MAX_VALUE;
18             for (int k = 0; k < list.size(); k++) {
19                 if (list.get(k) <= j) {
20                     if (count[j] > count[j - list.get(k)] + 1) {
21                         count[j] = count[j - list.get(k)] + 1;
22                     }
23                 } else {
24                     break;
25                 }
26             }
27         }
28         return count[n];
29     }
30 }

 

Perfect Squares

原文:http://www.cnblogs.com/beiyeqingteng/p/5662188.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!