标签:Count Training 2320 house long placed street each side
Problem Statement
There is a street with n * 2
plots, where there are n
plots on each side of the street. The plots on each side are numbered from 1
to n
. On each plot, a house can be placed.
Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answer may be very large, return it modulo 109 + 7
.
Note that if a house is placed on the ith
plot on one side of the street, a house can also be placed on the ith
plot on the other side of the street.
Example 1:
Input: n = 1 Output: 4 Explanation: Possible arrangements: 1. All plots are empty. 2. A house is placed on one side of the street. 3. A house is placed on the other side of the street. 4. Two houses are placed, one on each side of the street.
Example 2:
Input: n = 2 Output: 9 Explanation: The 9 possible arrangements are shown in the diagram above.
Constraints:
1 <= n <= 104
Video Tutorial
You can find the detailed video tutorial hereThought Process
A classic DP problem (Dynamic Programming) because it's either ask you a boolean yes or no questions, Or ask for extreme values, e.g., min, max, or just a number of solutions etc.- Two sides are independent, each side is similar to Climb Stairs, House Robber House Robber II
- Given each side is independent, the combo would be multiplied together.
- Implementation wise
- could use two variables to replace the array
- be careful about overflow (use long to cast back to int)
Solutions
1 public int countHousePlacements(int n) { 2 if (n < 0) { 3 return -1; 4 } 5 long divider = (long)(Math.pow(10, 9) + 7); 6 // could be replaced by two variables, similar to climb stairs, so space is O(1) as opposed to O(N) 7 long[] result = new long[n + 1]; 8 result[0] = 1; 9 result[1] = 2; 10 for (int i = 2; i <= n; i++) { 11 result[i] = result[i - 1] % divider + result[i - 2] % divider; 12 } 13 return (int)(result[n] * result[n] % divider); 14 }
Time Complexity: O(N) since going through each number till n
Space Complexity: O(1) if we use two variables to track, the above implementation is O(N) since an extra array is used.
References
标签:Count,Training,2320,house,long,placed,street,each,side 来源: https://www.cnblogs.com/baozitraining/p/16464560.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。