題目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;
}