Write a function that reverses a string. The input string is given as an array of characters char[]
.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
难点在于空间复杂度为1,而普通的迭代算法,question(n)需要空间来保存question(n-1)中间结果,O(N)
分治,需要将问题分解为独立的两个子问题,可以交换顺序
class Solution {
public:
void reverseString(vector<char>& s) {
help(0, s.size()-1, s);
}
void help(int begin, int end, vector<char>& s){
if(begin>=end)
return;
char temp = s[begin];
s[begin] = s[end];
s[end] = temp;
help(begin+1, end-1, s);
}
};
Swap Nodes in Pairs
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head|| !head->next)//!head情况
return head;
ListNode *temp;
temp = head->next;//node1
head->next = swapPairs(head->next->next);//从node2开始的子问题
temp->next = head;
return temp;
}
};
Reverse Linked List
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode *temp = reverseList(head->next);//此处将节点1开始全部反转了
head->next->next = head;//此处将节点0与1反转
head->next = NULL;
return temp;
}
};
带哈希表的费波那契数列
class Solution {
public:
unordered_map<int, int> temp;
int fib(int N) {
if(N == 0 || N == 1) return N;
unordered_map<int, int>::iterator p = temp.find(N);
if(p != temp.end()) return p->second;
int result = fib(N-1)+fib(N-2);
temp.insert(unordered_map<int, int>::value_type(N, result));
return result;
}
};
尾递归,递归在最后一句,不用重新分配栈空间
https://leetcode.com/explore/learn/card/recursion-i/256/complexity-analysis/2374/
求pow(x, n)
class Solution {
public:
double myPow(double x, int n) {
return help(x, n, 0, 1);
}
double help(double x, int n, int m, double acc){
if(m == n) return acc;
return (m < n)?help(x, n, m+1, x*acc):help(x, n, m-1, acc/x);
}
};
Runtime Error Message:AddressSanitizer: stack-overflow on address 0x7ffd1ea9aff8 (pc 0x000000406eb6 bp 0x7ffd1ea9b000 sp 0x7ffd1ea9b000 T0)
Last executed input:0.00001 2147483647
已经使用尾迭代了,还是会堆栈溢出,姿势不对?难道要使用二分法?