toastbin / DailyProblems

LeetCode
10 stars 2 forks source link

35.完全平方数 #36

Open toastbin opened 5 years ago

toastbin commented 5 years ago

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

示例 1:

输入: n = 12
输出: 3 
解释: 12 = 4 + 4 + 4.
示例 2:

输入: n = 13
输出: 2
解释: 13 = 4 + 9.
yj-man commented 5 years ago
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        System.out.println("请输入正整数:");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        int[] it = new int[n+1];

        for(int i = 1; i <= n; i ++) {
            it[i] = i;
            for(int j = 1; i - j*j >= 0; j ++) {
                it[i] = Math.min(it[i], it[i - j*j] +1);
            }
        }

        System.out.println(it[n]);
    }
}