Given four number a0, a1, a2, a3,..., ak
Find all possible expression to using + - * / with any '(',')' to generate a
result equals to target X.
上来就想了
1. 数字permutation (k!种)
2. 然后在数字之间插operator : +-*/ (k-1 spaces, total possibility 4^(k-1
))
3. 加括号,就是生成所有叶子数为k的树,简单起见就是用binary tree了
List GenTree(oprand[s..e])
{
List allTress = new List();
if(s==e)
allTrees.add(new Node(s));
return allTrees.
for i=s to e-1:
Node root = GenRoot(s, e, i)
List leftSubTrees = GenTree(oprand[s, i])
List rightSubTrees = GenTree(oprand[i+1, e])
allTress.addAll(GenFullTree(root, leftSubTrees,rightSubTrees)
return allTrees.
}
求结果就是post order traversal.
暴力解法有太多的重复计算了,求此题目简洁解法。