124.Perfect Squares

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.

给定一个正整数,求该正整数可以被被分解成完全平方数的个数。
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
采用动态规划的思想。
如果n为完全平方数,则f[n]=1;
否则f(n) = min{f(k)+f(n-k)},1<=k<=n/2

/**
	 * 给定一个正整数,求该正整数可以被被分解成完全平方数的个数。
	 * For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
	 * 采用动态规划的思想。
	 * 如果n为完全平方数,则f[n]=1;
	 * 否则f(n) = min{f(k)+f(n-k)},1<=k<=n/2
	 * @date 20160510
	 * @param n
	 * @return
	 */
	public int numSquares(int n) {
		
		if(n == 1){
			return 1;
		}
		int f[] = new int[n+1];//f[i]表示给定i时其对应的符合条件的完全平方数个数。
		f[1]=1;
		
		for(int i=2;i<=n;i++){
			/*首先判断是否为一个完全平方数*/
			double y = Math.sqrt(i);
			if( y - (int)y == 0){
				f[i] = 1;
				continue;
			}
			/*不为完全平方数时*/
			f[i] = f[1]+f[i-1];
			for(int k=2;k<=i/2;k++){
				if(f[k]+f[i-k]<f[i]){
					f[i] = f[k]+f[i-k];
				}
			}
		}
        return f[n];
    }

你可能感兴趣的:(124.Perfect Squares)