把正整数 n 转化成最少个数字的平方


 题目描述:

给一个正整数 n, 找到若干个完全平方数(比如1, 4, 9, ... )使得他们的和等于 n。你需要让平方数的个数最少。

给出 n = 12, 返回 3 因为 12 = 4 + 4 + 4。

给出 n = 13, 返回 2 因为 13 = 4 + 9。


这个题目的思路是用动态规划,设 f(n) 为所求的最少个数。 那么 f(n)=min(  f(i)+f(n-i)  ), 1<=i<=n,

我们不单单是要知道最小个数,还想要知道具体的数字,那么我们可以用一个二维数组来保存它们。


具体代码:



public class dtgh {
  
    
   
    public static int[][] extendedBottomUpCutRod( int n){  
      
        int[][] s = new int[2][n + 1];  // s[0][2]保存 n 所需最少平方因子的个数,s[1][2]保存n 所需的平方因子  
        s[0][0] = 0;  
        
        for(int j = 1; j <= n; j++){  
            int q = n;  
            for(int i = 1; i<=j; i++){  
                if (i*i<=j&&q>=1+s[0][j-i*i]) {
                    q=1+s[0][j-i*i];
                    s[1][j] = i;  
                }
                
            }  
            s[0][j] = q;  
        }  
        System.out.print("\n 最少个数: " + s[0][n]);  
        return s;  
    }  
      
  
    public static void printCutRodSolution( int n){  
        int result[][] = extendedBottomUpCutRod( n);  
        System.out.print("\n拆分方案方案:"+ n +"= ");  
        while(n > 0){  
            System.out.print(result[1][n]+"*"+result[1][n]);  
            n = n - result[1][n]*result[1][n];  
           
            if (n>0) {
                System.out.print(" + ");
            }
          
        }  
    }  
  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        
            printCutRodSolution(13);  
    }  
  

}

 
测试结果:






  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值