LeetCode的medium题集合(C++实现)六
1 Multiply Strings
Given two numbers represented as strings, return multiplication of the numbers as a string.Note: The numbers can be arbitrarily large and are non-negative.
该题实际就是利用字符串来解决大数的乘法问题。为了计算方便先将两组数翻转,将字符串转化为整数利用两个循环逐位相乘,将结果保存。然后逐位解决进位问题。
string multiply(string num1, string num2) {
int flag = 0, len1 = num1.length(), len2 = num2.length();
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
vector<int> mid(len1 + len2, 0);
string result;
for (int i = 0; i<len1; i++)
{
for (int j = 0; j<len2; j++)
{
int a = num1[i] - ‘0‘;
int b = num2[j] - ‘0‘;
mid[i + j] += a*b;
}
}
for (int m = 0; m<len1 + len2; m++)
{
int c = (mid[m] + flag) % 10;
flag = (mid[m] + flag) / 10;
mid[m] = c;
}
int n = len1 + len2 - 1;
while (mid[n] == 0)
{
n--; //去掉前面为0的元素
}
if (n<0) return result += ‘0‘;
for (; n >= 0; n--)
{
result += (‘0‘ + mid[n]);
}
return result;
}
2 Permutations
Given a collection of numbers, return all possible permutations.For example,[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
前面我们已经解决过nextPermutation问题,即可以求出一组数集的下一个排列,我们可以先将这组数按升序排列,然后循环求解下一个排列直到无解为止,此时可得到这组数全部的排列组合。该方法同时解决了Permutations II.
bool nextPermutation(vector<int>& nums) {
bool flag=true;
if (nums.size() < 2) return false;
int i, k;
for (i = nums.size() - 2; i >= 0; --i) if (nums[i] < nums[i+1]) break;
for (k = nums.size() - 1; k > i; --k) if (nums[i] < nums[k]) break;
if(i<0) flag=false;
if (i >= 0) swap(nums[i], nums[k]);
reverse(nums.begin() + i + 1, nums.end());
return flag;
}
vector<vector<int>> permute(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int> > res;
bool flag=true;
while(flag)
{
res.push_back(nums);
flag=nextPermutation(nums);
}
return res;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。