Cartesian Product - LintCode

We use the two-dimensional array setList[][] to represent the collection array, where each element in setList[i] is an integer and not the same. Find the Cartesian product of the sets setList[0],setList[1],…,setList[setList.length - 1].
In general, the Cartesian product of set A and set B, A×B = {(x,y)|x∈A∧y∈B}.

 注意事项
1 <= setList.length <= 5
1 <= setList[i].length <= 5

Example
Given setList = [[1,2,3],[4],[5,6]], return [[1,4,5],[1,4,6],[2,4,5 ],[2,4,6],[3,4,5],[3,4,6]].

解释:
[1,2,3]和[4]和[5,6]的笛卡尔积为[[1,4,5],[1,4,6],[2,4,5],[2,4,6],[3,4,5],[3,4,6]]

Given setList = [[1,2,3],[4]], returns [[1,4],[2,4],[3,4]].

解释:
[1,2,3]和[4]的笛卡尔积为[[1,4],[2,4],[3,4]]

ideas

#ifndef C935_H
#define C935_H
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
    /**
    * @param setList: The input set list
    * @return: the cartesian product of the set list
    */
    vector<vector<int>> getSet(vector<vector<int>> &setList) {
        // Write your code here
        vector<vector<int>> res;//存放最终结果
        vector<vector<int>> temp;//存放中间结果
        for (auto c : setList[0])
            res.push_back({ c });
        //对于setList[i],此时的结果为res,笛卡尔积为res中的每个数组分别添加setList[i]的每个元素
        for (int i = 1; i < setList.size(); ++i)
        {
            for (auto c : res)
            {
                for (auto t: setList[i])
                {
                    vector<int> v = c;
                    v.push_back(t);
                    temp.push_back(v);
                }
            }
            res = temp;
            temp.clear();
        }
        return res;
    }
};
#endif

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325390225&siteId=291194637