mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1306 from xiaofei-2020/dp29
添加(0198.打家劫舍.md):增加typescript版本
This commit is contained in:
@ -189,6 +189,29 @@ const rob = nums => {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
TypeScript:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function rob(nums: number[]): number {
|
||||||
|
/**
|
||||||
|
dp[i]: 前i个房屋能偷到的最大金额
|
||||||
|
dp[0]: nums[0];
|
||||||
|
dp[1]: max(nums[0], nums[1]);
|
||||||
|
...
|
||||||
|
dp[i]: max(dp[i-1], dp[i-2]+nums[i]);
|
||||||
|
*/
|
||||||
|
const length: number = nums.length;
|
||||||
|
if (length === 1) return nums[0];
|
||||||
|
const dp: number[] = [];
|
||||||
|
dp[0] = nums[0];
|
||||||
|
dp[1] = Math.max(nums[0], nums[1]);
|
||||||
|
for (let i = 2; i < length; i++) {
|
||||||
|
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
|
||||||
|
}
|
||||||
|
return dp[length - 1];
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user