注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
大家好,新手來這邊求點大米,順便分享一下,希望有幫助
這次題目是這個
Gridland is a 2D world divided into cells. We describe each cell as an (x,y) coordinate with (0,0) in the top left corner. From some cell (x,y), an inhabitant can move either horizontally or vertically to an adjacent cell, i.e. (x+1, y) or (x, y+ 1). We describe each possible minimum path as a sequence of horizontal and vertical moves denoted by the characters H and V. For exa"2 2 3", "5 8 1006", "6 6 36"], 每一組的都代表x, y, k.
當然可以用暴力解,先把所有組合列出來,再找,可是運算時間會過長,我的解法是用dp來解,backtracking. 這樣可以省去滿大的時間
- class Solution:
- def getSafePaths(self, journeys):
- # Write your code here
- #create dp array
- #using dynammic programming, due to the limitation of x and y is 10, I gave the range from 0~11
- dp = [[1 for i in range(11)] for j in range(11)]
- #the number of ways on the dp[i][j] position is equal dp[i-1][j] + dp[i][j-1]
- for i in range(1, 11):
- for j in range(1,11):
- dp[i][j] = dp[i-1][j] + dp[i][j-1]
- res = []
- #use for loop to take a look each paramater and split it by space
- for journey in journeys:
- paramater = journey.split()
- x = int(paramater[0])
- y = int(paramater[1])
- k = int(paramater[2])+1
- result = ""
- #from the dp[x][y] backtracking the path we want.
- #if dp[x-1][y] >= k, it means the path is start from H, otherwise, from V.
- #we need to reduce the number of combination which starts from H.
- while( x > 0 and y > 0):
- if dp[x-1][y] >= k:
- result += "H"
- x-=1
- else:
- result += "V"
- k-=dp[x-1][y]
- y-=1
- while y > 0:
- result += "V"
- y-=1
- while x > 0:
- result += "H"
- x-=1
- res.append(result)
- return res
- if __name__ == "__main__":
- nums = ['2 2 2', '2 2 3']
- result = Solution().getSafePaths(nums)
- print(result)
复制代码
他給了我十天去解這題,如果看不懂的話可以底下留言,我會幫你解答
新手求點大米 好過日子 謝謝各位
|