Leetcode每日随机2021/5/6

今天又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;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值