Leetcode_62_Unique Paths

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pistolove/article/details/43404205

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/43404205



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?


Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.


思路:

(1)题意为给定m行n列,求从第0行第0列走到第m行第n列的路径有多少条。

(2)对于本题,首先想到的是通过递归来实现,当行数为1或者列数为1时,路径只有一条;我们先从行开始,假设从第1行第1列元素开始,向右到达右下角,则可以看做是去除第一列后剩余行列对应路径,以函数f(m,n)表示路径条数,则有f(m,n)=f(1,n-1)+f(2,n-1),...,+f(n,n-1),而f(1,n)=f(m,1)=1,则通过递归即可得到答案,只是递归效率太低,Oj肯定会超时,所以,不能选用这种方法。

(3)考虑到m行n列正好对应一个二位数组,而我们发现f(1,n)=f(m,1)=1,所以,我们对整个二维数组进行拆分,假设拆分第一行,则第一行中任意位置作为终点对应的条数都为1,同理拆分第一列也是;这样,对应二维数组的第一行第一列的值就都为1了;假设数组为2*2,则我们发现到达右下角的路径数为f(2,2)=2=f(2,1)+f(1,2),正好为该位置对应上方和左方值之和;同理,当数组为3*3时,f(3,3)=6=f(3,2)+f(2,3)={f(3,1)+f(2,2)}+{f(1,3)+f{2,2}}={1+f(1,1)+f(1,1)}+{1+f(1,1)+f(1,1)}=6;同理,当数组为m*n时,f(m,n) = f(m-1,n)+f(m,n-1)=.......。所以,我们只需要对二维数组中每个位置遍历赋值即可得到最后的结果,详情见下方代码。

(4)希望本文对你有所帮助。


算法代码实现如下:

	/**
	 * @liqq 递归算法能够实现 但是会超时 oj不通过
	 */
	public static int get(int row, int col){
		if(row<=0 || col <=0) return 0;
		if(row==1) return 1;
		if(col==1) return 1;
		int result = 0;
		for (int i = 1; i <=row; i++) {
			result+=get(i,col-1);
		}
		return result;
	}

	/**
	 * @author 二维数组实现
	 */
	public static int getResult(int m, int n){
		int[][] arr   = new int[m][n];
		
		for (int i = 0; i < m; i++) {
			arr[i][0]=1;
		}
		
		for (int i = 0; i < n; i++) {
			arr[0][i]=1;
		}
		
		for (int i = 1; i < m; i++) {
			for (int j = 1; j < n; j++) {
				arr[i][j]=arr[i-1][j]+arr[i][j-1];
			}
		}
		
		return arr[m-1][n-1];
	}


Numbering Paths Numbering Paths

09-30

Problem DescriptionrnProblems that process input and generate a simple ``yes'' or ``no'' answer are called decision problems. One class of decision problems, the NP-complete problems, are not amenable to general efficient solutions. Other problems may be simple as decision problems, but enumerating all possible ``yes'' answers may be very difficult (or at least time-consuming). rnrnThis problem involves determining the number of routes available to an emergency vehicle operating in a city of one-way streets.rnrnGiven the intersections connected by one-way streets in a city, you are to write a program that determines the number of different routes between each intersection. A route is a sequence of one-way streets connecting two intersections. rnrnIntersections are identified by non-negative integers. A one-way street is specified by a pair of intersections. For example, j k indicates that there is a one-way street from intersection j to intersection k. Note that two-way streets can be modeled by specifying two one-way streets: j k and k j . rnrnConsider a city of four intersections connected by the following one-way streets: rnrn0 1rn0 2rn1 2rn2 3rnrnThere is one route from intersection 0 to 1, two routes from 0 to 2 (the routes are 0-1-2 and 0-2 ), two routes from 0 to 3, one route from 1 to 2, one route from 1 to 3, one route from 2 to 3, and no other routes. rnIt is possible for an infinite number of different routes to exist. For example if the intersections above are augmented by the street , there is still only one route from 0 to 1, but there are infinitely many different routes from 0 to 2. This is because the street from 2 to 3 and back to 2 can be repeated yielding a different sequence of streets and hence a different route. Thus the route 0-2-3-2-3-2 is a different route than 0-2-3-2 . rn rnrnInputrnThe input is a sequence of city specifications. Each specification begins with the number of one-way streets in the city followed by that many one-way streets given as pairs of intersections. Each pair j k represents a one-way street from intersection j to intersection k. In all cities, intersections are numbered sequentially from 0 to the ``largest'' intersection. All integers in the input are separated by whitespace. The input is terminated by end-of-file. rnrnThere will never be a one-way street from an intersection to itself. No city will have more than 30 intersections.rn rnrnOutputrnFor each city specification, a square matrix of the number of different routes from intersection j to intersection k is printed. If the matrix is denoted M, then M[j][k] is the number of different routes from intersection j to intersection k. The matrix M should be printed in row-major order, one row per line. Each matrix should be preceded by the string ``matrix for city k'' (with k appropriately instantiated, beginning with 0). rnrnIf there are an infinite number of different paths between two intersections a -1 should be printed. DO NOT worry about justifying and aligning the output of each matrix. All entries in a row should be separated by whitespace. rn rnrnSample Inputrn7 0 1 0 2 0 4 2 4 2 3 3 1 4 3rn5 rn0 2 rn0 1 1 5 2 5 2 1rn9rn0 1 0 2 0 3rn0 4 1 4 2 1rn2 0rn3 0rn3 1rn rnrnSample Outputrnmatrix for city 0rn 0 4 1 3 2rn 0 0 0 0 0rn 0 2 0 2 1rn 0 1 0 0 0rn 0 1 0 1 0rnmatrix for city 1rn 0 2 1 0 0 3rn 0 0 0 0 0 1rn 0 1 0 0 0 2rn 0 0 0 0 0 0rn 0 0 0 0 0 0rn 0 0 0 0 0 0rnmatrix for city 2rn -1 -1 -1 -1 -1rn 0 0 0 0 1rn -1 -1 -1 -1 -1rn -1 -1 -1 -1 -1rn 0 0 0 0 0

Redundant Paths

10-23

DescriptionnnIn order to get from one of the F (1 <= F <= 5,000) grazing fields (which are numbered 1..F) to another field, Bessie and the rest of the herd are forced to cross near the Tree of Rotten Apples. The cows are now tired of often being forced to take a particular path and want to build some new paths so that they will always have a choice of at least two separate routes between any pair of fields. They currently have at least one route between each pair of fields and want to have at least two. Of course, they can only travel on Official Paths when they move from one field to another. nnGiven a description of the current set of R (F-1 <= R <= 10,000) paths that each connect exactly two different fields, determine the minimum number of new paths (each of which connects exactly two fields) that must be built so that there are at least two separate routes between any pair of fields. Routes are considered separate if they use none of the same paths, even if they visit the same intermediate field along the way. nnThere might already be more than one paths between the same pair of fields, and you may also build a new path that connects the same fields as some other path.nInputnnLine 1: Two space-separated integers: F and R nnLines 2..R+1: Each line contains two space-separated integers which are the fields at the endpoints of some path.nOutputnnLine 1: A single integer that is the number of new paths that must be built.nSample Inputnn7 7n1 2n2 3n3 4n2 5n4 5n5 6n5 7nSample Outputnn2

Pathological Paths

01-08

DescriptionnnProfessor Pathfinder is a distinguished authority on the structure of hyperlinks in the World Wide Web. For establishing his hypotheses, he has been developing software agents, which automatically traverse hyperlinks and analyze the structure of the Web. Today, he has gotten an intriguing idea to improve his software agents. However, he is very busy and requires help from good programmers. You are now being asked to be involved in his development team and nto create a small but critical software module of his new type of software agents. nUpon traversal of hyperlinks, Pathfinder's software agents incrementally generate a map of visited portions of the Web. So the agents should maintain the list of traversed hyperlinks and visited web pages. One problem in keeping track of such information is that two or more different URLs can point to the same web page. For instance, by typing any one of the following five URLs, your favorite browsers probably bring you to the same web page, which as you may have visited is the home page of the ACM ICPC Ehime contest. nhttp://www.ehime-u.ac.jp/ICPC/nnhttp://www.ehime-u.ac.jp/ICPCnnhttp://www.ehime-u.ac.jp/ICPC/../ICPC/nnhttp://www.ehime-u.ac.jp/ICPC/./nnhttp://www.ehime-u.ac.jp/ICPC/index.htmlnnYour program should reveal such aliases for Pathfinder's experiments. nWell, . . . but it were a real challenge and to be perfect you might have to embed rather complicated logic into your program. We are afraid that even excellent programmers like you could not complete it in five hours. So, we make the problem a little simpler and subtly unrealistic. You should focus on the path parts (i.e. /ICPC/, /ICPC, /ICPC/../ICPC/, /ICPC/./, and /ICPC/index.html in the above example) of URLs and ignore the scheme parts (e.g. http://), the server parts (e.g. www.ehime-u.ac.jp), and other optional parts. You should carefully read the rules described in the sequel since some of them may not be based on the reality of today's Web and URLs. nEach path part in this problem is an absolute pathname, which specifies a path from the root directory to some web page in a hierarchical (tree-shaped) directory structure. A pathname always starts with a slash (/), representing the root directory, followed by path segments delimited by a slash. For instance, /ICPC/index.html is a pathname with two path segments ICPC and index.html. nAll those path segments but the last should be directory names and the last one the name of an ordinary file where a web page is stored. However, we have one exceptional rule: an ordinary file name index.html at the end of a pathname may be omitted. For instance, a pathname /ICPC/index.html can be shortened to /ICPC/, if index.html is an existing ordinary file name. More precisely, if ICPC is the name of an existing directory just under the root and index.html nis the name of an existing ordinary file just under the /ICPC directory, /ICPC/index.html and /ICPC/ refer to the same web page. Furthermore, the last slash following the last path segment can also be omitted. That is, for instance, /ICPC/ can be further shortened to /ICPC. However, /index.html can only be abbreviated to / (a single slash). nYou should pay special attention to path segments consisting of a single period (.) or a double period (..), both of which are always regarded as directory names. The former represents the directory itself and the latter represents its parent directory. Therefore, if /ICPC/ refers to some web page, both /ICPC/./ and /ICPC/../ICPC/ refer to the same page. Also /ICPC2/../ICPC/ refers to the same page if ICPC2 is the name of an existing directory just under the root; notherwise it does not refer to any web page. Note that the root directory does not have any parent directory and thus such pathnames as /../ and /ICPC/../../index.html cannot point to any web page. nYour job in this problem is to write a program that checks whether two given pathnames refer to existing web pages and, if so, examines whether they are the same.nInputnnThe input consists of multiple datasets. The first line of each dataset contains two positive integers N and M, both of which are less than or equal to 100 and are separated by a single space character. nThe rest of the dataset consists of N + 2M lines, each of which contains a syntactically correct pathname of at most 100 characters. You may assume that each path segment enclosed by two slashes is of length at least one. In other words, two consecutive slashes cannot occur in any pathname. Each path segment does not include anything other than alphanumerical characters (i.e. `a'-`z', `A'-`Z', and `0'-`9') and periods (`.'). nThe first N pathnames enumerate all the web pages (ordinary files). Every existing directory name occurs at least once in these pathnames. You can assume that these pathnames do not include any path segments consisting solely of single or double periods and that the last path segments are ordinary file names. Therefore, you do not have to worry about special rules for index.html and single/double periods. You can also assume that no two of the N pathnames npoint to the same page. nEach of the following M pairs of pathnames is a question: do the two pathnames point to the same web page? These pathnames may include single or double periods and may be terminated by a slash. They may include names that do not correspond to existing directories or ordinary files. nTwo zeros in a line indicate the end of the input.nOutputnnFor each dataset, your program should output the M answers to the M questions, each in a separate line. Each answer should be "yes" if both point to the same web page, "not found" if at least one of the pathnames does not point to any one of the first N web pages listed in the input, or "no" otherwise.nSample Inputnn5 6n/home/ACM/index.htmln/ICPC/index.htmln/ICPC/general.htmln/ICPC/japanese/index.htmln/ICPC/secret/confidential/2005/index.htmln/home/ACM/n/home/ICPC/../ACM/n/ICPC/secret/n/ICPC/secret/index.htmln/ICPCn/ICPC/../ICPC/index.htmln/ICPCn/ICPC/general.htmln/ICPC/japanese/.././n/ICPC/japanese/./../n/home/ACM/index.htmln/home/ACM/index.html/n1 4n/index.html/index.htmln/n/index.html/index.htmln/index.htmln/index.html/index.htmln/..n/index.html/../..n/index.html/n/index.html/index.html/..n0 0nSample Outputnnnot foundnnot foundnyesnnonyesnnot foundnnot foundnyesnnot foundnnot found

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试