合并多个数组到另一个数组 [英] Combine multiple array to another array
本文介绍了合并多个数组到另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要像这样组合2个数组
i want combine 2 array like this
示例1:
Arr1 = ['A','B','C'],
Arr2 = ['D','E']
将成为
Arr3 = [
['A','D'],['A','E'],['B','D'],['B','E'],['',''] ....
]
示例2:
Arr1 = ['A','B','C'],
Arr2 = ['D','E']
Arr3 = ['G','H']
将成为
Arr4 = [
['A','D','G'],['A','E','G'],['','','']....
]
任何想法或建议我的算法都可以如此感谢
Any idea or suggest me algorithm can be like this thanks so much
推荐答案
The problem you suggest is very similar to this Leetcode Challenge. The idea is to use Backtracking
Psuedo PsedoCode:
result := string Array
CartesianProduct(rowIndex, ArrayList, stringSoFar):
if rowIndex equal ArrayList.size:
Add stringSoFar to result
return
for(eachItem in ArrayList[rowIndex])
CartesianProduct(rowIndex +1 , ArrayList, stringSoFar + eachItem)
return
所有的计算,可以像 CartesianProduct(0,要乘以Array的列表,)
假设您的 ArrayList = [['A'],['C','D']]
。而 CP
是 CartesianProduct
CP(0, AL, "")
(Take 'A')/
/
CP(1, AL, "A") (stringSoFar becomes 'A')
(Take C) / \(Take 'D'.Second Iteration with second array['C', 'D'])
/ \
CP(2, AL, "AC") CP(2, AL, "AD")
/ \
rowIndex equal size. rowIndex equals listSize i.e No more list to look
Add "AC" and return Add stringsoFar ("AD") to result and rerturn
我对Leetcode问题的解决方案(但在C ++中)。希望它能给您一些想法,用PHP编写
My solution to the Leetcode problem(but in C++). Hopefully it'll give you some idea to write in PHP
class Solution {
public:
map<char, vector<string>> values {
{'2', vector<string>{"a", "b", "c"}},
{'3', vector<string>{"d", "e", "f"}},
{'4', vector<string>{"g", "h", "i"}},
{'5', vector<string>{"j", "k", "l"}},
{'6', vector<string>{"m", "n", "o"}},
{'7', vector<string>{"p", "q", "r", "s"}},
{'8', vector<string>{"t", "u", "v"}},
{'9', vector<string>{"w", "x", "y", "z"}}
};
vector<string> answer;
void doComb(int index, string digits, string sofar)
{
if(index == digits.size())
{
if(sofar != "")
{
answer.push_back(sofar);
}
return;
}
for(auto lett : values[digits[index]])
{
doComb(index + 1, digits, sofar + lett);
}
return;
}
vector<string> letterCombinations(string digits) {
doComb(0, digits, "");
return answer;
}
};
这篇关于合并多个数组到另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文