神奇的口袋 用两个栈实现队列

在这里插入图片描述
思路:
采用递归思想: ①物品n个,物品体积逐一放入weight[]中 ②递归函数count(int s,int n) : 其
中s为剩余物品重量,n为剩余可选的物品个数
则分以下两步递归求解:
a.从后往前装,装上weight[n]后,若剩余物品仍然有解
则count(s-weight[n],n-1);
b.若装了weight[n]后,无解,则删除该包,尝试第n-1个
count(s,n-1)

import java.util.*;
public class Main {
static int[] weight;
static int N;
static int count=0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
N = input.nextInt();
weight = new int[N+1];
for (int i = 1; i <= N; i++) {
weight[i] = input.nextInt();
} 
count(40,N);
System.out.println(count);
}
} 
 Public static void count(int s,int n) {
//如果正好装满
if(s==0) {
++count;
return ;
}
//是s<0或n<1则不能完成
if(s<0||(s>0&&n<1))
return ;
count(s-weight[n],n-1);
count(s,n-1);
}
}

在这里插入图片描述
代码:

import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
} 
public int pop() {
if(stack1.empty()&&stack2.empty()){
throw new RuntimeException("Queue is empty!");
} 
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
} 
return stack2.pop();
}
} 

装箱:
拆箱:
在这里插入图片描述
在这里插入图片描述
泛型:
在这里插入图片描述
good and gbc
解析:1.传参 将实参的地址引用传递给形参
2.形参str改变了指向,实参str并没有改变
3.char[0]='g’改变了数组的首元素
4.形参的作用范围:函数的大括号结束


版权声明:本文为qq_44331767原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。