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 mid(len1 + len2, 0);
string result;
for (int i = 0; i= 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& 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> permute(vector& nums) {
sort(nums.begin(),nums.end());
vector > res;
bool flag=true;
while(flag)
{
res.push_back(nums);
flag=nextPermutation(nums);
}
return res;
}