题目1:矩形覆盖
/**矩形覆盖 * 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。 * 请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法? * 比如n=3时,2*3的矩形块有3种覆盖方法: */
public int RectCover(int target) {
/*
//递归
if(target<0){
throw new IllegalArgumentException("输入的数应大于0");
}
if(target==1||target==2||target==0){
return target;
}
return RectCover(target-1)+RectCover(target-2);*/
//非递归
if(target<0){
throw new IllegalArgumentException("输入的数应大于0");
}
if(target<3){
return target;
}else{
int res;
int n=3;
ArrayList<Integer> resl = new ArrayList<>();
resl.add(0);
resl.add(1);
resl.add(2);
while (n<=target){
resl.add(resl.get(n-1)+resl.get(n-2));
n+=1;
}
return resl.get(target);
}
}
题目2:斐波那契数列
/**斐波那契数列 * 大家都知道斐波那契数列,现在要求输入一个整数n, * 请你输出斐波那契数列的第n项(从0开始,第0项为0, * 第1项是1)。 * n<=39 */
public int Fibonacci(int n) {
if(n<0||n>39){
throw new IllegalArgumentException("输入的数应大于0");
}
if (n== 1 ||n==0) {
return n;
}
if(n==2){
return 1;
}
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
题目3:二进制中1的个数
/** * 二进制中1的个数 * 题目描述 * 输入一个整数,输出该数二进制表示中1的个数。 * 其中负数用补码表示。 */
public int NumberOf1(int n) {
int count = 0;
int nc = 1;
while (nc != 0) {
if ((nc & n) != 0) {
count++;
}
nc <<= 1;
}
return count;
}
题目4:合并两个排序的链表
/**合并两个排序的链表 * 输入两个单调递增的链表,输出两个链表合成后的链表, * 当然我们需要合成后的链表满足单调不减规则 */
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode head;
ListNode temp;
if(list1==null&&list2!=null){
head=list2;
return head;
}
if(list2==null&list1!=null){
head=list1;
return head;
}
if(list1==null&&list2==null){
return null;
}
if(list1.val<=list2.val){
head=list1;
list1=list1.next;
}else {
head=list2;
list2=list2.next;
}
temp=head;
while (list1!=null&&list2!=null){
if(list1.val<list2.val){
temp.next=list1;
list1=list1.next;
temp=temp.next;
}else {
temp.next=list2;
list2=list2.next;
temp=temp.next;
}
}
if(list1==null){
temp.next=list1;
}
if(list2==null){
temp.next=list2;
}
return head;
}