62. Unique Paths
1.确定dp数组的下标及定义
dp[i][j]从(0,0)到(i,j)的不同路径数量
2.确定递推公式
dp[i][j] = dp[i-1][j] + dp[i][j-1];
3.初始化
dp[i][0]和dp[0][j]都是1;
4.遍历顺序,从左上到右下
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m,vector<int>(n,0));
for(int i=0; i<m; i++) dp[i][0] = 1;
for(int j=0; j<n; j++) dp[0][j] = 1;
for(int i=1; i<m;i++){
for(int j=1; j<n; j++){
dp[i][j] = dp[i-1][j]+ dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};
63. Unique Paths II
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1) return 0;
vector<vector<int>> dp(m, vector<int>(n,0));
for(int i=0; i<m && obstacleGrid[i][0] != 1; i++){
dp[i][0] = 1;
}
for(int j=0; j<n && obstacleGrid[0][j] != 1; j++){
dp[0][j] = 1;
}
for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
if(obstacleGrid[i][j] == 1) dp[i][j] = 0;
else dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};
1.不要忘记在设置初始值的时候也要去除掉有障碍的部分
2.不要忘记去除掉在开头和结尾出现障碍的情况
343. Integer Break
class Solution {
public:
int integerBreak(int n) {
vector<int> dp(n+1);
dp[2] = 1;
for(int i=3; i<=n; i++){
for(int j=1; j<i-1; j++){
dp[i] = max(dp[i], max(j*(i-j), j*dp[i-j]));
}
}
return dp[n];
}
};
1.dp[i] 数字i能拆分出的最大乘积
2.第二个循环的条件为i-1不是n-1
状态转移方程好难,自己完全想不到😭,之后再来看吧
86. Partition List
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* dummy1 = new ListNode(0);
ListNode* dummy2 = new ListNode(0);
ListNode* p1= dummy1;
ListNode* p2 = dummy2;
ListNode* cur = head;
while(cur != NULL){
if(cur->val < x){
p1->next = cur;
p1 = p1->next;
}
else{
p2->next = cur;
p2 = p2->next;
}
ListNode* tmp = cur->next;
cur->next = NULL;
cur = tmp;
}
p1->next = dummy2->next;
return dummy1->next;
}
};
1.分为两个小链表,一个小于,一个大于等于
2.要记得把原来的链表断开
206. Reverse Linked List
递归思想
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode* last = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return last;
}
};
92. Reverse Linked List II
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy;
for(int i=0; i<left-1; i++){
pre = pre->next;
}
ListNode* cur = pre->next;
for(int i=left; i<right; i++){
ListNode* tmp = pre->next;
pre->next = cur->next;
cur->next = cur->next->next;
pre->next->next = tmp;
}
return dummy->next;
}
};