zoukankan      html  css  js  c++  java
  • 279. Perfect Squares

    • Total Accepted: 48616
    • Total Submissions: 142008
    • Difficulty: Medium

    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.

    穷举会: Time Limit Exceeded

    加入几个分支判断,除去大部分没用分支

    public class Solution {
        public int numSquares(int n) {
            if(n == 0){
                return 0;
            }
            int count = 0;
            while (count*count <= n){
                if(count*count == n){
                    return 1;
                }
                count++;
    
            }
    
            int nums [] = new int[count];
            DFS(n,nums,count-1,0);
            return result;
        }
    
        int result = Integer.MAX_VALUE;
        private void DFS(int n,int[] nums,int selectNum,int preCount){  // count:平方数最大是几,n:sum target,nums 1——count
            if(n == 0){
                int newResult = getResult(nums);
                if(result > newResult){  //time limit error 优化:加入preCount,统计到目前为止已用的的数量
                    result = newResult;
                }
                return;
            }
            if(preCount >= result){
                return;
            }
            if(selectNum >= 1){
                int maxLoop = n / selectNum /selectNum;
                if(preCount+maxLoop > result) return;  //time limit error 优化:加入preCount,统计到目前为止已用的的数量
                for(int i = maxLoop;i >= 0;i--){
                    nums[selectNum] = i;
                    DFS(n-i*selectNum*selectNum,nums,selectNum-1,preCount+i);
                }
            }
        }
    
        private int getResult(int[]nums){
            int result = 0;
            for(int i = 1;i < nums.length;i++){
    //            System.out.print(nums[i] + " ");
                result+=nums[i];
            }
    //        System.out.println("result:"+result);
            return result;
        }
    }
  • 相关阅读:
    跨域请求
    django数据模型中关于on_delete, db_constraint的使用
    rest-framework之分页器
    跨域请求
    相对路径与绝对路径
    html常用标签
    ES6中字符串扩展
    javascript中startswith和endsWidth 与 es6中的 startswith 和 endsWidth
    Angular6 组件树结构优化
    docker限制容器内存使用上限
  • 原文地址:https://www.cnblogs.com/1995hxt/p/5862807.html
Copyright © 2011-2022 走看看