Leetcode (algorithm article)-Brute force (DFS, BFS, permutation)

Source: Internet
Author: User

Introduction

Now the recruitment process of the Internet, algorithm problem is essential, for like I have not engaged in the ACM to eat melon masses, fortunately there are leetcode, save me from fire and fire. As a result, intermittent, brush some problems, some of which are worth careful taste, and now some of the problems to tidy up, some of the solution is my own writing, but also some solution is to refer to the discuss in the answer, as a small summary of autumn strokes. Because the level is limited, the code is not well written, the choice of topics can only be used to get started, I hope you forgive me.

Brute Force hack

Brute force hack, as far as I understand it, is to traverse the whole tree of search, no Shanfanjiujian, tight is the search and match alone.

1. Basic brute force hack: For the most basic brute force hack, it is to take out all possible, and compare the conditions in the topic, until find the answer that conforms to test instructions.

Example : Chicken and rabbit cage problem, known x head, y feet, ask the number of rabbits and chickens.

Solution : Counting the number of chickens (or rabbits) from 0~x, calculate whether the number of feet is Y.

2, DFS: Depth First search. From the original state, select any state, along this state until there is no next state, this time backtracking, to the current state of the previous state, select another state to traverse. DFS is often used on code implementations Recursivemethod to implement.

Example 1:leetcode 129. Sum Root to Leaf Numbers

Given a binary tree containing digits from only 0-9 , each root-to-leaf path could represent a number.

An example is the Root-to-leaf path 1->2->3 which represents the number 123 .

Find The total sum of all root-to-leaf numbers.

For example,

    1   /   2   3

The Root-to-leaf path 1->2 represents the number 12 .
The Root-to-leaf path 1->3 represents the number 13 .

Return the sum = + = 25 .

Solution: The most intuitive way of thinking is to find all the paths, record all the values on the path, and sum the code as follows:

classSolution { Public:    intRET =0; intSumnumbers (treenode*root) {        if(Root = = nullptr)returnret; Getsum (Root,root-val); returnret; }//Recursive callvoidGetsum (treenode* root,intPreval) {        if(root->left==nullptr&&root->right==nullptr) {ret+=Preval; return; }        if(root->left) Getsum (root->left,preval*Ten+root->left->val); if(root->right) Getsum (root->right,preval*Ten+root->right->val); return; }};

In addition, DFS can often be used to find all available states:

Example Two: Leetcode200. Number of Islands

Given a 2d grid map ‘1‘ of S (land) ‘0‘ and S (water), count the number of islands. An island is surrounded by water and are formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the grid is all surrounded by water.

Example 1:

11110
11010
11000
00000

Answer:1

Example 2:

11000
11000
00100
00011

Answer:3

idea: in this topic, think of all 1 (up and down) is an island, to the number of islands in the array. The main idea is to start with any point that is a value of 1, mark all reachable points as visited, and if all reachable points are visited or 0, it means that all the data in the island has been searched, then you can find the next island. Finally, the number of islands can be obtained. In the following code, the visited point is marked as 0, and if the value of the adjacent point is 1, the description is extensible.

Solution:

classSolution { Public:    intdir[4][2]={{-1,0},{1,0},{0,-1},{0,1}}; intM,n,ret =0; intNumislands (vector<vector<Char>>&grid) {        if(Grid.empty ())return 0; M= Grid.size (), n = grid[0].size ();  for(intI=0; i<m;i++){             for(intj=0; j<n;j++){                if(grid[i][j]=='1') {DFS (I,j,grid); ++ret; }            }        }        returnret; }        voidDfsintSintt,vector<vector<Char>>&grid) {
If you have already visited or are over-bounded, you do not need to expandif(s<0|| s>=m| | t<0|| t>=n| | grid[s][t]=='0'){ return; }
Marked as has visited Grid[s][t]='0';
Extend down one state for recursive access for(intI=0;i<4; i++) {DFS (s+dir[i][0],t+dir[i][1],grid); } return; }};

3.BFS: Breadth-First search, a method that is relative to DFS, starts with the initial state and iterates through all the remaining states in the form of "radiating". For state traversal, there are a lot of similarities between the scenarios that BFS and DFS can use, such as the Leetcode129 above, and the BFS solution.

BFS generally uses the queue implementation: Put the initial state into the queue, when the team out, all the non-visited status of the status of the queue for subsequent access. A typical application of the BFS is to find the (shortest) path, from the initial state to the target State, since the BFS can guarantee that the steps from the initial state to the state in the current queue are the same for each traversal, and another typical application is for some sort of "layered" situation, for a certain state, All of its subsequent states have the same properties.

For example 1:leetcode 490, but this question is paid, I have only read the solution, and did not do, the maze is the most classic application of BFS. The topic and solution can refer to a blogger's blog that I have always admired: https://www.cnblogs.com/grandyang/p/6381458.html

Example 2:leetcode 542. The Matrix

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between and adjacent cells is 1.

Example 1:
Input:

0 0 00 1 00 0 0

Output:

0 0 00 1 00 0 0

Example 2:
Input:

0 0 00 1 01 1 1

Output:

0 0 00 1 01 2 1

Note:

    1. The number of elements of the given matrix would not exceed 10,000.
    2. There is at least one 0 in the given matrix.
    3. The cells is adjacent in directions:up, down, left and right.

Solution: This problem is a typical application of "layered" scene, for each 0, its surrounding non-0 points of the same state: the nearest 0 distance is 1, and then the center of these 1, the diffusion of the second layer has the same properties.

classSolution { Public:    intdir[4][2]={{0,1},{0,-1},{-1,0},{1,0}}; #definePII pair<int,int>#defineMP Make_pairVector<vector<int>> Updatematrix (vector<vector<int>>&matrix) {        intm =matrix.size (); if(m==0)returnMatrix; intn = matrix[0].size (); Queue<pii>Q;  for(intI=0; i<m;i++){             for(intj=0; j<n;j++){                if(matrix[i][j]==0) {Q.push (MP (I,J)); }Else{Matrix[i][j]=Int_max; }            }        }         while(!Q.empty ()) {PII tmp=Q.front ();            Q.pop ();  for(intk=0;k<4; k++){                intA = tmp.first+dir[k][0],b = tmp.second+dir[k][1]; if(a<0|| a>=m| | b<0|| B>=n)Continue; if(Matrix[a][b]<=matrix[tmp.first][tmp.second])Continue; MATRIX[A][B]=min (matrix[a][b],matrix[tmp.first][tmp.second]+1);            Q.push ({A, b}); }        }        returnMatrix; }};

Example 3:102. Binary Tree level Order traversal

Another typical application of BFS is the hierarchical traversal of trees or graphs, which is relatively basic and is not mentioned here.

4, permutation: that is, the whole arrangement, you can get the full arrangement of 1~n

In C + +, you can use the interface inside the STL to implement, for example, to find an array of all permutations:

class Solution {public:    vector<vector<int>> permute (vector<  int>& nums) {        sort (nums.begin (), Nums.end ());        Vector<vector<int>> ret;        Ret.push_back (nums);          while (Next_permutation (Nums.begin (), Nums.end ())) {            ret.push_back (nums);        }         return ret;    }};

Before using this function, be aware that you need to sort the array so that you can detect whether the current arrangement has been generated.

In addition, permutation can also be used to find a subset (M selected k), that is, using M's full array of the first K.

The complexity of permutation is O (n!), which can be used only when the data volume is small.

Leetcode (algorithm article)-Brute force (DFS, BFS, permutation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.