深度优先搜索。
class Solution {
public:
vector<vector<int>> result;
vector<int> list;</p>
<pre><code>void search(int now, int k, int n, int sum)
{
if (list.size() == k &amp;&amp; sum == n)
{
resul……
因为矩阵的特殊性,所有从左上角顶点开始搜索即可。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = matrix.size() - 1;
int cols = matrix[0].size() - 1;
int x = 0;
int y = cols;<……
求二叉搜索树的第k个数,中序遍历生成二叉搜索树,存入数组中,然后输出第k个即可。
class Solution {
public:
vector&lt;int&gt; list;
void queryTree(TreeNode * node)
{
if (NULL == node)
{
return;
}
if (NULL != node-&gt;left……
求数组中,是否存在两个相同元素的小标差小于k。hash题目。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> mNums;
mNums.clear();
for (int i = 0;i < nums.size();i++)
{
map<int,int>::ite……
计算两个矩形的面积和,有可能有重叠区域。
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int bx,by,tx,ty;
bx = A > E ? A : E;
by = B > F ? B : F;</p>
<pre><code> tx = C &lt; ……
取出数组[正整数]中的数,使和最大,但是规则是不能去相邻的数。
可以枚举2^n中情况,复杂度太高。可以用一维动态规划的解法 f(n) = max(f(n-1), nums[n] + f(n-2));
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() <= 0)
{
return 0;
}……
求二叉树中,每层最右边的节点的值,序列化每层二叉树,然后输出每层最后一个节点即可。
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans(0);
if (NULL == root)
{
return ans;
}
queue<TreeNode *>……
给定数组中,所有数都是成对出现,但是只有两个数,不成对,求出这两个数。
相信一个数的情况大家都知道,使用异或即可解决问题,两个数的话,异或了之后得到的是a^b,但是如何找出a与b呢,从a^b可以得,该值一定不为0,只需要取任何一个位数上不为0的数,将数组分为两类,在异或即可。
class Solution {
public:
ve……
反转单链表。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (NULL == head)
{
return head;
}
ListNode * before = NULL;
ListNode * now = head;
ListNode * next = now->next;</p>
<pre><code> ……
输入数组a1,a2,a3…
生成数组a23, a1a3, a1*a2,但是希望能够在o(n)的时间内解决,且不能使用出发。
用两个额外的数组记录ai前和ai后的乘积即可。
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int size = nums.size();
……