1. 程式人生 > 其它 >笛卡爾乘積問題

笛卡爾乘積問題

技術標籤:LeetCodeleetcode笛卡爾積

笛卡爾乘積問題的判別

笛卡爾問題的一個特點是有很多個種類的子結果的拼接。目前遇到的只是字串的拼接。

通用解決思路

  • 分步求解結果,最後拼接;

例題

Leetcode 816.模糊座標

class Solution {
public:
    vector<string> addSymbol(string s) {
        vector<string> res;
        int length = s.length();
        for(int i = 1; i <= length - 1
; i++) { string temp = s; // 剪枝 if(temp[0] == '0' && i > 1) continue; if(temp[length-1] == '0') continue; temp.insert(i, "."); res.push_back(temp); } if(s == "0" || s[0] != '0') res.push_back
(s); return res; } vector<string> ambiguousCoordinates(string S) { // S去除兩邊的括號 string s = S.substr(1, S.size()-2); int length = s.length(); // 結果儲存 vector<string> res; // 遍歷逗號插入位置 for(int i = 1; i <= length - 1; i++)
{ // 分割字串 vector<string> x = addSymbol(s.substr(0,i)); vector<string> y = addSymbol(s.substr(i, length-i)); // 笛卡爾乘積 for(auto i : x) { for(auto j : y) { string temp = "(" + i + ", " + j + ")"; res.push_back(temp); } } } return res; } };