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;
        }
    }
  • 相关阅读:
    C++高精度乘法
    经典的7种排序算法 原理C++实现
    c++ STL
    二分查找c++
    洛谷P1111 修复公路
    01背包写法
    c++编码规范
    github教程
    windows10锁定屏幕聚焦图片导出
    week 6 Spring history and design philosophy
  • 原文地址:https://www.cnblogs.com/1995hxt/p/5862807.html
Copyright © 2011-2022 走看看