- John’s backyard garden
John wants to build a back garden on the empty space behind his home. There are two kinds of bricks now, one is 3 dm high and the other is 7 dm high. John wants to enclose a high x dm wall. If John can do this, output YES, otherwise NO.
Example
Example 1:
Input : x = 10
Output : “YES”
Explanation :
x = 3 + 7:That is, you need one batch of 3 dm height bricks and one batch of 7 dm height bricks.
Example 2:
Input : x = 5
Output : “NO”
Explanation:
John can not enclose a high 5 dm wall with 3 dm height bricks and 7 dm height bricks.
Example 3:
Input : x = 13
Output : “YES”
Explanation :
x = 2 * 3 + 7:That is, you need two batch of 3 dm height bricks and one batch of 7 dm height bricks.
Notice
X is an integer, and it’s range is [3, 1000].
解法1:完全背包变种。
代码如下:
class Solution {
public:
/**
* @param x: the wall's height
* @return: YES or NO
*/
string isBuild(int x) {
string result;
vector<int> A = {3, 7};
vector<int> dp(x + 1, 0);
dp[0] = 1;
for (int i = 0; i <= 1; ++i) {
for (int j = A[i]; j <= x; ++j) {
dp[j] = dp[j] || dp[j - A[i]];
}
}
if (dp[x]) return "YES";
else return "NO";
}
};