LeetCode的medium题集合(C++实现)十五

1 Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note:

Elements in a subset must be in non-descending order.

The solution set must not contain duplicate subsets.

For example,If nums = [1,2,3], a solution is:

[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]

首先对该数据集进行排序,利用循环遍历得到n个有1个元素的子集,并且采用递归的方法向得到的子集中增加数据,得到元素更多的子集。

 void dst(int i,vector<int>& res, vector<int>& nums, vector<vector<int>>& result)
    {
        int len=nums.size();
        if(i>=len) return ;
        for(;i<len;i++)
        {
            res.push_back(nums[i]);
            result.push_back(res);
            dst(i+1,res,nums,result);
            res.pop_back();
        }
    }
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int> > result;
        vector<int> res;
        sort(nums.begin(),nums.end());
        int len=nums.size();
        for(int i=0;i<len;i++)
        {
            res.push_back(nums[i]);
            result.push_back(res);
            dst(i+1,res,nums,result);
            res.pop_back();
        }
        res.clear();
        result.push_back(res);
        return result;
    }

2 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.

For example,Given board =

[

[“ABCE”],

[“SFCS”],

[“ADEE”]

]

word = “ABCCED”, -> returns true,

word = “SEE”, -> returns true,

word = “ABCB”, -> returns false.

该题类似迷宫问题,采用回溯的方法,分别向上下左右四个方向搜索下一个字母,采用一个额外的容器标记之前该字母是否已访问过。

 bool search(vector<vector<char>>& board, int i, int j, string word,vector<vector<bool> >& visited)
   {
      if(word.length()==0)
      return true;
    //四个走向
       vector<vector<int> >direction = { {-1,0},{1,0},{0,-1},{0,1}};  

    for (int k=0;k<direction.size();k++) {
        int ii = i + direction[k][0];
        int jj = j + direction[k][1];
        if ( ii>=0&&ii<board.size()&&
             jj>=0&&jj<board[i].size()&&
             board[ii][jj]==word[0]&&
             visited[ii][jj]==false) {
            visited[ii][jj] = true;
            if (word.length()==1 || search(board,ii,jj,word.substr(1),visited)) {
                return true;
            }
            visited[ii][jj] = false;
        }
    }
    return false;
  }
    bool exist(vector<vector<char>>& board, string word) {
       if(board.size()==0) return false;
       if(word.length()==0) return true;
       int m=board.size();
       int n=board[0].size();
       vector<vector<bool> > visited(m,vector<bool>(n,false));
       for(int i=0;i<m;i++)
       {
           for(int j=0;j<n;j++)
           {
               if(board[i][j]==word[0])
               {
                   visited[i][j]=true;
                   if(word.length()==1||search(board,i,j,word.substr(1),visited))
                   return true;
                   visited[i][j]=false;
               }
           }
       }
       return false;
    }
时间: 2024-11-05 15:00:26

LeetCode的medium题集合(C++实现)十五的相关文章

LeetCode的medium题集合(C++实现)十

1 Permutation Sequence The set [1,2,3,-,n] contains a total of n! unique permutations.Given n and k, return the kth permutation sequence. 使用Next Permutation循环k次可以得到序列,但leetcode上提交会出现时间超过限制.下面采用数学法: 在n!个排列中,第一位元素相同的排列总是有(n?1)!个,如果p=k/(n?1)!,那么排列的第一位元素

LeetCode的medium题集合(C++实现)十四

1 Sort Colors Given an array with n objects colored red, white or blue, sort them 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,

LeetCode的medium题集合(C++实现)十二

1 Sqrt(x) Implement int sqrt(int x).Compute and return the square root of x. 因为这里都是整数,可以直接采用二分法求解 int mySqrt(int x) { if (x <= 1) return x; int begin = 1, end =x, mid = 0; while (begin<=end) { mid = (begin + end) / 2; if (mid<x / mid) //不要用乘法判断,否

LeetCode的medium题集合(C++实现)十六

1 Remove Duplicates from Sorted Array II Follow up for "Remove Duplicates":What if duplicates are allowed at most twice?For example,Given sorted array nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of

LeetCode的medium题集合(C++实现)十一

1 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

LeetCode的medium题集合(C++实现)五

1 Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. 可以采用递归的方法解决这个问题,当找到一组数之和

LeetCode的medium题集合(C++实现)六

1 Multiply Strings Given two numbers represented as strings, return multiplication of the numbers as a string.Note: The numbers can be arbitrarily large and are non-negative. 该题实际就是利用字符串来解决大数的乘法问题.为了计算方便先将两组数翻转,将字符串转化为整数利用两个循环逐位相乘,将结果保存.然后逐位解决进位问题. s

LeetCode的medium题集合(C++实现)四

1 Next Permutation Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending or

LeetCode的medium题集合(C++实现)九

1 Jump Game Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.Determine if you are able to reach the last index. 利用两指针法