题解 | #最少的完全平方数#

最少的完全平方数

http://www.nowcoder.com/practice/4b2f5d4c00f44a92845bdad633965c04

完全背包问题 思路:要求最少的完全平方数

输入n即为 体积

对于每一个完全平方数都是物品

物品 1 4 9

对应体积为 1 4 9

无价值,要求的是最少的完全数,所以不需要价值

要等于n 即为至少装满体积v1 也就是之前完全背包的第二问

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] dp = new int[n + 1];
        Arrays.fill(dp,Integer.MAX_VALUE);
        dp[0] = 0;
        //输入5
        for(int i = 1; i * i <= n; i++) {//物品 1 2 
            for(int j = i * i; j <= n; j++) {//容量为5 
                dp[j] = Math.min(dp[j], dp[j - i * i] + 1);
            }
        }
        System.out.println(dp[n]);
    }
}
全部评论

相关推荐

09-15 15:53
Java
Elastic90:我看到的是东软的人在耐心回应,而那位实习生跟在发疯似的
投递东软集团等公司10个岗位
点赞 评论 收藏
分享
09-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务