Array - 62. 63. 64. 66. 73. 74. 75. 78. 79. 80

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];
    }
};
64. Minimum Path Sum

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];       
    }
};
66. Plus One

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;
    }
};
73Set Matrix Zeroes

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

74Search 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;
    }
};
75Sort 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++]);     
        }
    }
};

78Subsets

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

提示:

  1. Initially: [[]]
  2. Adding the first number to all the existed subsets: [[], [1]];
  3. Adding the second number to all the existed subsets: [[], [1], [2], [1, 2]];
  4. 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;
    }
};

79Word 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;
    }
};

80Remove 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 of nums being 1, 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] 
   }
*/





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ValueError: setting an array element with a sequence是一个常见的机器学习问题。这个错误通常出现在尝试将一个序列赋值给一个数组的元素时。根据引用、和的描述,这个问题可能与numpy数组的形状不匹配有关。 首先,需要检查代码中numpy数组的形状是否正确。如果数组的形状不正确,尝试重新调整数组的维度,以确保每个元素都具有相同的形状。 另外,还需要确认是否在使用数组的索引操作时出现了错误。在numpy中,使用索引操作时需要确保索引的维度和数组的形状是一致的。 如果仍然无法解决问题,可以尝试使用其他方法来解决该问题。例如,可以尝试使用循环来逐个赋值数组的元素,而不是直接赋值一个序列。 综上所述,当遇到ValueError: setting an array element with a sequence时,需要检查numpy数组的形状和索引操作,同时可以尝试使用其他方法来解决该问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [ValueError: setting an array element with a sequence.](https://blog.csdn.net/weixin_51197745/article/details/116591165)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [解决python-报错----ValueError: setting an array element with a sequence.](https://blog.csdn.net/qwerpoiu66/article/details/130902870)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值