对了,例子里面用的背包问题的方程忘记写了,这里把比较复杂的一个写了,简单的部分就不写了,看懂了的小伙伴应该都可以很轻松的写出来:dp[i][j]=max(dp[i-1][j-x],dp[i-1][j]); 具体使用的时候,根据我们的问题要求,这个方程是会变化的,核心是递归的方程传递原则,只要清楚这个,就知道为啥最优了。

相关推荐

import java.util.Scanner;public class demo {public static void main(String[] args) {//移除链表元素//构造链表1-->4-->2-->4Scanner sc = new Scanner(System.in);int n = sc.nextInt();//链表共有节点个数sc.nextLine();//构造单链表  尾插法ListNode head = null;//head一旦确定,就不再移动ListNode tail = null;//随着新节点的加入,不断向后移动if (n > 0){for (int i = 1; i <= n; i++){int val = sc.nextInt();//输入链表ListNode newNode = new ListNode(val);if (head == null){//插入第一个节点时,head既是头又是尾head = newNode;tail = head;}else{tail.next = newNode;tail = tail.next;}}}sc.nextLine();int target = sc.nextInt();//需要移除的目标值//如果头节点本身就要删除while (head != null && head.val == target){head = head.next;//直接将head后移}//判断是否为空if (head == null){return;}//处理头节点之后的节点ListNode current = head;while (current.next != null){if (current.next.val == target){//找到目标,则移除current.next = current.next.next;}else {//没找到,继续向后current = current.next;}}while (head != null){System.out.print(head.val + " ");head = head.next;}}}class ListNode{int val;ListNode next;ListNode(int val){this.val = val;}}
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务