LeetCode 面试题14- I. 剪绳子
中等
-
题目:LeetCode 面试题14- I. 剪绳子
给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]…k[m-1] 。请问 k[0]k[1]…*k[m-1] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
注意:2 <= n <= 58。 -
示例:
输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1
输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36
- 方法:动态规划或者数学方法。
- cpp代码实现:
class Solution
{
public:
int cuttingRope(int n)
{
vector<int>dp(n + 1);
dp[1] = 1;
for(int i = 2; i <= n; ++i)
{
for(int j = 1; j < i; ++j)
dp[i] = max(dp[i], max(dp[i - j] * j, (i - j) * j));
}
return dp[n];
}
};
LeetCode 面试题14- II. 剪绳子 II
中等
-
题目:给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]…k[m] 。请问 k[0]k[1]…*k[m] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
注意:2 <= n <= 1000( I 和 II 不同之处)。 -
示例:
输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1
输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36
- 方法:数学规律(最优3)。
- cpp代码实现:
class Solution
{
public:
int cuttingRope(int n)
{
if(n == 2)
return 1;
if(n == 3)
return 2;
int mod = 1000000007;
long long res = 1;
while(n > 4)
{
res *= 3;
res %= mod;
n -= 3;
}
res *= n;
res %= mod;
return (int)res;
}
};
LeetCode 面试题35.复杂链表的复制
中等
-
题目:请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
-
示例:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
- 方法:第一步,完成链表的复制(包括节点的复制和随机指针的复制);第二步,将链表一分为二即可。
(1->2->3 转化为 1->1->2->2->3->3 再拆分) - cpp代码实现:
class Solution
{
public:
Node* copyRandomList(Node* head)
{
if(head == NULL)
return head;
Node* cur = head;
//节点的复制
while(cur != NULL)
{
Node* copyNode = new Node(cur->val);
copyNode->next = cur->next;
cur->next = copyNode;
cur = cur->next->next;
}
cur = head;
//复制节点的随即指针的复制
while(cur != NULL)
{
if(cur->random != NULL)
cur->next->random = cur->random->next;
cur = cur->next->next;
}
Node* copyHead = head->next;
cur = head;
Node* copyCur = head->next;
//将链表一分为二
while(cur != NULL)
{
cur->next = cur->next->next;
cur = cur->next;
if(copyCur->next != NULL)
{
copyCur->next = copyCur->next->next;
copyCur = copyCur->next;
}
}
return copyHead;
}
};
【写在最后】
大家,学习的时候千万不要想太多,容易失眠,太影响学习的状态了。和朋友聊了两句,然后我的大脑开始膨胀,中午躺了一个小时都没有睡着,我太难了···········学校明天又是一批返校的,反正不是我,我也不知道自己啥时候能返校,我也不敢问呢~~~~~~~~~~