Merge pull request #1306 from xiaofei-2020/dp29

添加(0198.打家劫舍.md):增加typescript版本
This commit is contained in:
程序员Carl
2022-05-27 10:17:22 +08:00
committed by GitHub

View File

@ -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];
};
```