今天做的两个题目都比较简单,所以一起打卡一下
189题打家劫舍,就是简单的动态规划,首先我们要定义子问题,将totle[i]表示为打劫前i家所能打劫到的最多钱,其中初识值totle[0]的值为0,因为它没有打劫房子,totle[1]的值为nums[0],因为它就打劫了一件房子,然后开始分析写递推关系式,totle[n]=max(totle[n-1],totle[n-2]+nums[n-1]),其中前一项表示,第n家不打劫,后一项表示第n家打劫,两者去较大值就好。这就是一个简单的动态规划的题目。
public class t198 {
public int rob(int[] nums) {
int n=nums.length;
if(n==1) return nums[0];
int[] totle=new int[n+1];
totle[0]=0;
totle[1]=nums[0];
for (int i = 2; i < n + 1; i++) {
totle[i]=Math.max(totle[i-1],totle[i-2]+nums[i-1]);
}
return totle[n];
}
}
第199题二叉树的右视图,这个题目就是宽度优先搜索,一般这种都是用队列来找每一层的最右端的节点,记录下来即可。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class t199 {
public List<Integer> rightSideView(TreeNode root) {//宽度有限搜索
List<Integer> ret = new ArrayList<>();
if (root == null) return ret;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (! queue.isEmpty()) {
for (int i = queue.size(); i > 0; i--) {
TreeNode temp = queue.poll();
if (i == 1) ret.add(temp.val);
if (temp.left != null) queue.add(temp.left);
if (temp.right != null) queue.add(temp.right);
}
}
return ret;
}
}