62. Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
提示:首先很容易想到
path[i][j] = path[i - 1][j] + path[i][j - 1];
但是在计算时只需要两列就足够了,之后发现前一列也可以省去,只用一列。vector cur(m,1)
答案:
class Solution {
public:
int uniquePaths(int m, int n) {
if(m > n) return uniquePaths(n, m );
vector<int> cur(m, 1);
for(int j = 1; j < n; j++){
for(int i = 1; i < m; i++){
cur[i] += cur[i - 1];
}
}
return cur[m - 1];
}
};
63. Unique Paths II
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1
and 0
respectively in the grid.
Note: m and n will be at most 100.
Example 1:
Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2
提示:方法一:多加一行一列的 vector, dp[0][1] = 1;
方法二:01互换,如果1 执行加。
答案:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
dp[0][1] = 1;
for(int i = 1; i <= m; i++){
for(int j = 1; j <=n; j++){
if(!obstacleGrid[i - 1][j - 1])
dp[i][j] = dp[i -1][j] + dp[i][j - 1];
}
}
return dp[m][n];
}
};
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example:
Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum.
提示:思路类似unique path,计算left与up,然后计算其他。这个过程可以简化为两列,到一列,节省空间。
答案:
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<int> cur(m, grid[0][0]);
for(int i = 1; i < m; i++){
cur[i] = cur[i - 1] + grid[i][0];
}
for(int j = 1; j < n; j++){
cur[0] = cur[0] + grid[0][j];
for(int i = 1; i < m; i++){
cur[i] = min(cur[i - 1],cur[i]) + grid[i][j];
}
}
return cur[m -1];
}
};
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.
提示:The answer is amazing.灵活的使用for。
答案:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
for(int i = digits.size(); i--; digits[i] = 0)
if(digits[i]++ < 9)
return digits;
digits[0]++;
digits.push_back(0);
return digits;
}
};
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
提示:col0保存第一列是否原本就有0;第一步将 left与up里相应的元素置零;第二步根据第一步将相应元素置零,注意此时遍历 行时是逆序的,因为第一行影响其他元素,先改变就错了
答案:
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int col0 = 1, rows = matrix.size(), cols = matrix[0].size();
for(int i = 0; i < rows; i++){
if(matrix[i][0] == 0) col0 = 0;
for(int j = 1; j < cols; j++)
if(matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
for(int i = rows - 1; i >= 0; i--){
for(int j = cols - 1; j >= 1; j--)
if(matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if(col0 == 0) matrix[i][0] = 0;
}
}
};
74. Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true
提示:因为题目给出的矩阵比较特殊,可以看做排好序的链表处理,二分查找
答案:
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
int n = matrix.size();
int m = matrix[0].size();
int l = 0, r = m * n - 1;
while (l != r){
int mid = (l + r - 1) >> 1;
if (matrix[mid / m][mid % m] < target)
l = mid + 1;
else
r = mid;
}
return matrix[r / m][r % m] == target;
}
};
75. Sort Colors
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library's sort function for this problem.
提示:将2移到右边,将0移到左边,注意while语句的顺序应该对应for语句的判断条件
答案:
class Solution {
public:
void sortColors(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
for(int i = 0; i <= right; i++){
//由于i与right比较,所以带有right的while语句在前
while(nums[i] == 2 && i < right) swap(nums[i], nums[right--]);
while(nums[i] == 0 && i > left) swap(nums[i], nums[left++]);
}
}
};
78. Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
提示:
- Initially:
[[]]
- Adding the first number to all the existed subsets:
[[], [1]]
; - Adding the second number to all the existed subsets:
[[], [1], [2], [1, 2]]
; - Adding the third number to all the existed subsets:
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
.
答案:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> subs(1,vector<int>());
for(int i = 0; i < nums.size(); i++){
int n = subs.size();
for(int j = 0; j < n; j++){
subs.push_back(subs[j]);
subs.back().push_back(nums[i]);
}
}
return subs;
}
};
79. Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false.
提示:递归、访问标记
答案:
class Solution {
private:
bool exist(vector<vector<char>>& board, int i, int j, const string word, int step){
if(step == word.size()) return true;
if(i < 0 || i == board.size() || j < 0 || j == board[0].size() || board[i][j] != word[step])
return false;
board[i][j] = '#';//board[x][y] ^= 128;
bool existFlag = exist(board, i + 1, j, word, step + 1) || exist(board, i, j + 1, word, step + 1) ||
exist(board, i - 1, j, word, step + 1) || exist(board, i, j - 1, word, step + 1);
board[i][j] = word[step];// board[x][y] ^= 128;
return existFlag;
}
public:
bool exist(vector<vector<char>>& board, string word) {
if(board.empty()) return false;
const int m = board.size();
const int n = board[0].size();
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(exist(board, i, j, word, 0))
return true;
}
}
return false;
}
};
80. Remove Duplicates from Sorted Array II
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,1,2,2,3], Your function should return length =5
, with the first five elements ofnums
being1, 1, 2, 2
and 3 respectively. It doesn't matter what you leave beyond the returned length.
提示:两个指针,一个指向插入位置,一个遍历指针,后者要与前前面的元素做比较
答案:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int i = 0;
for(int x : nums){
if(i < 2 || x > nums[i - 2])
nums[i++] = x;
}
return i;
}
};
/* int location = 0;
for(int i = 0; i < nums.size(); i++){
if(location < 2 || nums[i] > nums[i - 2])
nums[location++] = nums[i]
}
*/