某公司测试题(二)---完全平方数最少

题目:

给一个正整数 n, 找到若干个完全平方数(比如1, 4, 9, … )使得他们的和等于 n。你需要让平方数的个数最少。
给出 n = 12, 返回 3 因为 12 = 4 + 4 + 4。
给出 n = 13, 返回 2 因为 13 = 4 + 9。

动态规划的思路,代码及注释如下:

package tuyamobile;

import java.util.ArrayList;
import java.util.List;

/*
 * @author 黄斌
 * 建立一组映射关系
 * 例如:数组索引:1  2  3  4  5  6  7  8  9  10 11 12
 * 对应的值:          1  2  3  1  2  3  4  2  1  2  5  3
 * 这样可以使用递推关系
 */
public class TestTwo
{

    public int getRes(int n)
    {

        int[] a = new int[10000];

        a[0] = 0;
        a[1] = 1;
        a[2] = 2;

        for(int i = 2;i<=n;i++){
            if(judge(i)){
                a[i] = 1;
                continue;
            }
            ArrayList<Integer> list = new ArrayList<>();
            for(int x = 1;x<=i/2;x++){
                list.add(a[x]+a[i-x]);
            }

            a[i] = getMin(list);
        }

        return a[n];
    }

    public int getMin(List<Integer> list){

        int min = list.get(0);
        for(Integer value:list){
            if(value<min){
                min = value;
            }
        }

        return min;

    }

    public boolean judge(int n)
    {

        double a = Math.sqrt(n);

        int b = (int) a;

        if (b * b == n)
            return true;
        return false;
    }


    //测试
    public static void main(String[] args)
    {
        int n = 5;
        System.out.println(new TestTwo().judge(4));
        System.out.println(new TestTwo().getRes(2));
        System.out.println(new TestTwo().getRes(3));
        System.out.println(new TestTwo().getRes(4));
        System.out.println(new TestTwo().getRes(5));
        System.out.println(new TestTwo().getRes(6));
        System.out.println(new TestTwo().getRes(7));
        System.out.println(new TestTwo().getRes(8));
        System.out.println(new TestTwo().getRes(9));
        System.out.println(new TestTwo().getRes(10));
        System.out.println(new TestTwo().getRes(11));
        System.out.println(new TestTwo().getRes(12));
        System.out.println(new TestTwo().getRes(13));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值