代码随想录算法训练营第三八天| 279.完全平方数 139.单词拆分
今日任务
279.完全平方数
139.单词拆分
279.完全平方数
题目链接: . - 力扣(LeetCode)
class Solution {
public int numSquares(int n) {
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
int item = (int)Math.sqrt(n);
dp[0] = 0;
for (int i = 1; i <= item; i++) {
for (int j = 0; j <= n; j++) {
if (j >= i * i && dp[j - i * i] != Integer.MAX_VALUE) {
dp[j] = Math.min(dp[j], dp[j - i * i] + 1);
}
}
}
return dp[n];
}
}
139.单词拆分
题目链接: . - 力扣(LeetCode)
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
HashSet<String> set = new HashSet<>(wordDict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j <= i; j++) {
if (set.contains(s.substring(j, i)) && dp[j] == true) {
dp[i] = true;
}
}
}
for (int i = 0; i < dp.length; i++) {
System.out.println("dp " + i + " is: " + dp[i]);
}
return dp[s.length()];
}
}