您的位置:首页 > 编程语言 > C语言/C++

343. Integer Break 等

2016-10-23 11:26 260 查看

343. Integer Break

原题:

Given a positive integer n, break it into the sum of at least two positive integers and maximize

the product of those integers. Return the maximum product you can get.

For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return

36 (10 = 3 + 3 + 4).

Note: You may assume that n is not less than 2 and not larger than 58.

翻译题意

给一个大于2小于28的数字,拆成大于2个的数字组合,使他们的乘积最大,并返回最大乘积。

例如:f(2) = 1 * 1 = 1; f(10) = 3 * 3 * 4 = 36;

因为计算难度小,罗列出2~11的情况可以发现:

f(2) = 1 * 1f(7) = 3 * 4
f(3) = 1 * 2f(8) = 3 * 3 * 2
f(4) = 2 * 2f(9) = 3 * 3 * 3
f(5) = 3 * 2f(10) = 3 * 3 * 4
f(6) = 3 * 3f(11) = 3 * 3 * 3 * 2
大于5的数字,数字3的数量越多越好,其次是数字2和4.

因此很简单能写出如下代码:

class Solution {
public:
int integerBreak(int n) {
vector<int> res = {0,0,1,2,4};
if (n <= 4) {
return res
;
} else {
int ret = 1;
while(n>=3) {
ret *= 3;
n -= 3;
}
switch(n) {
case 0:
case 1:
return ret/3*(3+n);
default:
return ret * n;
}
}
}
};


38. Count and Say

原题:

The count-and-say sequence is the sequence of integers beginning

as follows: 1, 11, 21, 1211, 111221, …

1 is read off as “one 1” or 11. 11 is read off as “two 1s” or 21. 21

is read off as “one 2, then one 1” or 1211. Given an integer n,

generate the nth sequence.

Note: The sequence of integers will be represented as a string.‘

翻译题意

数数然后念出来:有这么一个列表,每个元素都是把上一个元素“念出来”,比如1211念做:“1个1,1个2,2个1”,因此组合成新元素就是:“111221”,从1开始以此类推。

输入为整数n,返回它对应的念出来的数字。

根据题意可以发现,标准的递归定义,用递归函数很容易写出:

class Solution {
public:
string countAndSay(int n) {
if (n==1) {
return "1";
}
string last = countAndSay(n-1);
char first = last[0];
int count = 1;
string cur;
for(int i=1; i<last.size(); i++) {
if (last[i] == first) {
count++;
} else {
cur+= to_string(count) + first;
first = last[i];
count = 1;
}
}
cur+= to_string(count) + first;
return cur;
}
};


为了效率,很容易改造成非递归函数:

class Solution {
public:
string countAndSay(int n) {
string last = "1";
char first = last[0];
int count = 1;
string cur;
for (int i=1; i<n; i++) {
first = last[0];
count = 1;
cur = "";
for(int i=1; i<last.size(); i++) {
if (last[i] == first) {
count++;
} else {
cur+= to_string(count) + first;
first = last[i];
count = 1;
}
}
last = cur + to_string(count) + first;
}
return last;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode