今天看啥
热点:

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 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;
    }

www.bkjia.comtruehttp://www.bkjia.com/cjjc/1000582.htmlTechArticleLeetCode的medium题集合(C++实现)六 1 Multiply Strings Given two numbers represented as strings, return multiplication of the numbers as a string.Note: The numbers can be arbi...

相关文章

相关搜索: C++

帮客评论

视觉看点