Leetcode Perfect Squares
2016-01-13 16:36
176 查看
Problem
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
3because
12 = 4 + 4 + 4; given n =
13, return
2because
13 = 4 + 9.
Solution 1 - pure recursion
求n 的perfect square, 可以化简成求 n 减去若干个 i*i之后 的数的perfect square.class Solution { public: int numSquares(int n) { if(n <= 1) return n; int rst = n; for( int i = 2; i*i <= n; i++){ int a = n / (i * i), b = n % (i * i); rst = min (rst, numSquares(b) + a); } return rst; } };
Solution 2 - recursion with memory
用一个数字,纪录上面的过程中重复值。class Solution { int helper( int n, vector<int>& arr){ if(arr != -1) return arr ; int rst = n; for( int i = 2; i*i <= n; i++){ int a = n / (i * i), b = n % (i * i); rst = min (rst, helper(b, arr) + a); } arr = rst; return rst; } public: int numSquares(int n) { if(n <= 1) return n; vector<int> arr(n+1, -1); helper(n, arr); return arr ; } };
Solution 3 - DP
其实上面的解法二已经很接近DP了dp[ x + y*y ] = min( dp[ x+ y*y ] , dp[ x ] + 1 );
class Solution { public: int numSquares(int n) { if(n <= 1) return n; vector<int> dp(n+1, INT_MAX); for (int i = 1; i * i <= n; i++) { dp[i * i] = 1; } for (int i = 1; i <= n; i++) { for (int j = 1; i + j * j <= n; j++) { dp[i + j * j] = min(dp[i] + 1, dp[i + j * j]); } } return dp ; } };
相关文章推荐
- 基于Android中dp和px之间进行转换的实现代码
- Android中dip、dp、sp、pt和px的区别详解
- LFC1.0.0 版本发布
- Android px、dp、sp之间相互转换
- HP data protector软件学习1--基本角色与基本工作流程
- HP data protector软件学习2--软件组成与界面介绍
- android中像素单位dp、px、pt、sp的比较
- Android对px和dip进行尺寸转换的方法
- Android根据分辨率进行单位转换-(dp,sp转像素px)
- android 尺寸 dp,sp,px,dip,pt详解
- DP问题各种模型的状态转移方程
- Yet Another Sudoku Solver in Python
- 考查嵌入式C开发人员的最好的十道题~答案(zz hecrics的BLOG)
- POJ-1695-Magazine Delivery-dp
- nyoj-1216-整理图书-dp
- TYVJ1193 括号序列解题报告
- 对DP的一点感想
- TYVJ上一些DP的解题报告
- soj1005. Roll Playing Games
- 01背包问题