public class Solution {
public int numSquares(int n) {
// All perfect squares less than n
List<Integer> moves = new ArrayList<>();
for(int i = 1; i <= n; i++){
if(i * i <= n) moves.add(i * i);
else break;
}
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
int lvl = 0;
queue.offer(0);
while(!queue.isEmpty()){
int size = queue.size();
lvl ++;
for(int i = 0; i < size; i++){
int sum = queue.poll();
for(int j = moves.size() - 1; j >= 0; j--){
int next = moves.get(j);
if(sum + next > n || visited.contains(sum + next)){
continue;
} else if(sum + next == n){
return lvl;
} else {
visited.add(sum + next);
queue.offer(sum + next);
}
}
}
}
return -1;
}
}
再仔细观察一下这题:
我们要凑出来一个和正好是 n 的选择组合;
能选的元素是固定数量的 perfect square (有的会超)
一个元素可以选多次;
这就是背包啊!
public class Solution {
public int numSquares(int n) {
// All perfect squares less than n
int[] dp = new int[n + 1];
Arrays.fill(dp, n + 1);
dp[0] = 0;
for(int i = 1; i <= n; i++){
for(int j = 1; j * j <= n; j++){
if(i - j * j >= 0) dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
}
}
return dp[n];
}
}
注意点 2 : 对称轴 -b / 2 * a 的时候括号顺序是 (double) -b / (2 * a)
第一次 AC 的代码~ 太粗糙,得改改。
public class Solution {
public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
int[] rst = new int[nums.length];
// Is a straight line
if(a == 0){
if(b > 0){
for(int i = 0; i < nums.length; i++){
rst[i] = a * nums[i] * nums[i] + b * nums[i] + c;
}
} else {
for(int i = 0; i < nums.length; i++){
rst[nums.length - i - 1] = a * nums[i] * nums[i] + b * nums[i] + c;
}
}
return rst;
}
double symmetricAxis = -((double) b / (2*a));
int left = 0;
int right = nums.length - 1;
int index = (a < 0) ? 0: nums.length - 1;
int step = (a < 0) ? 1: -1;
while(left <= right){
double leftDis = Math.abs(nums[left] - symmetricAxis);
double rightDis = Math.abs(nums[right] - symmetricAxis);
if(leftDis > rightDis){
rst[index] = a * nums[left] * nums[left] + b * nums[left] + c;
left ++;
} else {
rst[index] = a * nums[right] * nums[right] + b * nums[right] + c;
right --;
}
index += step;
}
return rst;
}
}
这题比较简洁的写法如下,明天学习一个。
这种写法的核心是只看 a 的 “正负”,无所谓 0.
If a > 0; the smallest number must be at two ends of orgin array;
If a < 0; the largest number must be at two ends of orgin array;
换句话说,a 的符号可以直接确定 two pointer 两端一定有一个 “最大/最小” 的值,每次 O(1) 计算一下就好,也能处理直线的情况。
public class Solution {
public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
int n = nums.length;
int[] sorted = new int[n];
int i = 0, j = n - 1;
int index = a >= 0 ? n - 1 : 0;
while (i <= j) {
if (a >= 0) {
sorted[index--] = quad(nums[i], a, b, c) >= quad(nums[j], a, b, c)
? quad(nums[i++], a, b, c)
: quad(nums[j--], a, b, c);
} else {
sorted[index++] = quad(nums[i], a, b, c) >= quad(nums[j], a, b, c)
? quad(nums[j--], a, b, c)
: quad(nums[i++], a, b, c);
}
}
return sorted;
}
private int quad(int x, int a, int b, int c) {
return a * x * x + b * x + c;
}
}