- 一、
LeetCode第2題,兩數相加遞歸解法,執行用時擊敗99.93%的用戶,內存消耗擊敗94.26%的用戶。
- 二、遞歸代碼
class Solution {
int addValue = 0;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null && addValue != 0)
return l1 = new ListNode(1);
if(l1 == null && l2 == null)
return null;
if(l1 == null){
int temp = (l2.val + addValue)%10;
addValue = (l2.val + addValue)/10;
l2.val = temp;
l2.next = addTwoNumbers(l1,l2.next);
return l2;
}
if(l2 == null){
int temp = (l1.val + addValue)%10;
addValue = (l1.val + addValue)/10;
l1.val = temp;
l1.next = addTwoNumbers(l1.next,l2);
return l1;
}
int temp = (l1.val + l2.val + addValue) % 10;
addValue = (l1.val + l2.val + addValue) / 10;
l1.val = temp;
l1.next = addTwoNumbers(l1.next ,l2.next);
return l1;
}
}