1. 程式人生 > 實用技巧 >11.20

11.20

537. 複數乘法

難度中等47

給定兩個表示複數的字串。

返回表示它們乘積的字串。注意,根據定義 i2 = -1 。

示例 1:

輸入: "1+1i", "1+1i"
輸出: "0+2i"
解釋: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i ,你需要將它轉換為 0+2i 的形式。

示例 2:

輸入: "1+-1i", "1+-1i"
輸出: "0+-2i"
解釋: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i ,你需要將它轉換為 0+-2i 的形式。 

注意:

  1. 輸入字串不包含額外的空格。
  2. 輸入字串將以 a+bi 的形式給出,其中整數 a
    b 的範圍均在 [-100, 100] 之間。輸出也應當符合這種形式

解答:主要使用sscanf,將字串分離

class Solution {
public:
    string complexNumberMultiply(string x, string y) {
        int a, b, c, d;
        sscanf(x.c_str(),"%d+%di", &a, &b);
        sscanf(y.c_str(), "%d+%di", &c, &d);
        return to_string(a * c - b * d) + "+" + to_string(a * d + b * c) + "i";
    }
};

90. 子集 II

難度中等346

給定一個可能包含重複元素的整數陣列 nums,返回該陣列所有可能的子集(冪集)。

說明:解集不能包含重複的子集。

示例:

輸入: [1,2,2]
輸出:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

解答:直接bfs搜尋

class Solution {
public:
    vector<int>path;
    vector<vector<int>>res;
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        dfs(nums, 0);
        return res;
    }
    void dfs(vector<int>& nums, int u){
        if(u == nums.size()){
            res.push_back(path);
            return ;
        }
        int k = u + 1;
        while(k < nums.size() && nums[k] == nums[u])k++;
        for(int i = 0; i <= k - u; i++){
            dfs(nums, k);
            path.push_back(nums[u]);
        }
        for(int i = 0; i <= k - u; i++){
            path.pop_back();
        }
    }
};

78. 子集

難度中等884

給定一組不含重複元素的整數陣列 nums,返回該陣列所有可能的子集(冪集)。

說明:解集不能包含重複的子集。

示例:

輸入: nums = [1,2,3]
輸出:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

解法一:使用位運算

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>>res;
        int n = nums.size();
        for(int i = 0; i < 1 << n; i++){
            vector<int>path;
            for(int j = 0; j < n; j++){
                if(i >> j & 1)path.push_back(nums[j]);
            }
            res.push_back(path);
        }
        return res;
    }
};

解法二:使用bfs

class Solution {
public:
    vector<int>path;
    vector<vector<int>>res;
    vector<vector<int>> subsets(vector<int>& nums) {
        dfs(nums, 0);
        return res;
    }
    void dfs(vector<int>& nums, int u){
        if(u == nums.size()){
            res.push_back(path);
            return ;
        }
        path.push_back(nums[u]);
        dfs(nums, u + 1);
        path.pop_back();
        dfs(nums, u + 1);
    }
};