题
今天又AC了,这三题以前好像都做过。
思
今天是经典专场啊。
第一题
leetcode第二题,看了下我一年多前的代码,跟现在的真比不了,写的太臭了,今天写的就很简洁。
第二题
这题是给我印象很深的一题,这题我也做过,可以说是我第一次碰到要用堆来解决的问题。
第三题
这题也是老经典了,就是一个普通的dfs,做下判重和剪枝就能过,为了剪枝多减一点,最好排下序,从大到小依次添加。
代码
第一题
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null;
ListNode tail = null;
int flag = 0;
while (l1 != null || l2 != null || flag != 0) {
int temp = flag;
if (l1 != null) {
temp += l1.val;
l1 = l1.next;
}
if (l2 != null) {
temp += l2.val;
l2 = l2.next;
}
ListNode node = new ListNode(temp % 10);
flag = temp / 10;
if (head == null) {
head = node;
}else {
tail.next = node;
}
tail = node;
}
return head;
}
}
第二题
class Solution {
public int furthestBuilding(int[] heights, int bricks, int ladders) {
Queue<Integer> queue = new PriorityQueue<Integer>();
for (int i = 0; i < heights.length - 1; i++) {
if (heights[i + 1] > heights[i]) {
queue.offer(heights[i + 1] - heights[i]);
if (queue.size() > ladders) {
int temp = queue.poll();
if (temp > bricks) {
return i;
} else {
bricks -= temp;
}
}
}
}
return heights.length - 1;
}
}
第三题
class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Stack<Integer> stack = new Stack<Integer>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
dfs(candidates.length,0, candidates, target);
return res;
}
public void dfs(int idx,int sum, int[] candidates, int target) {
if (sum > target) {
return;
}
if (sum == target) {
List<Integer> list = new ArrayList<Integer>();
for (Integer i : stack) {
list.add(candidates[i]);
}
list.sort((a,b)->a-b);
if (!contains(list)) {
res.add(list);
}
return;
}
for (int i = idx - 1; i >= 0; i--) {
stack.push(i);
dfs(i, sum + candidates[i], candidates, target);
stack.pop();
}
}
public boolean contains(List<Integer> list) {
for (List<Integer> temp : res) {
if (temp.size() == list.size()) {
boolean same = true;
for (int i = 0; i < list.size(); i++) {
if (temp.get(i) != list.get(i)) {
same = false;
break;
}
}
if (same) {
return true;
}
}
}
return false;
}
}