leetcode 666. Path Sum IV

来源:互联网 发布:三国志群英会java 编辑:程序博客网 时间:2024/06/06 19:33

写在前面

leetcode AC率越往后感觉好题出现的概率越高了,当然本题还是contest 43的一道题,题目不算难,但是我当时的解法是直接构造二叉树,虽然直接,但不聪明。对时间复杂度和空间复杂度都有影响,新的解法是比较优秀的方法。

题目描述

If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers.

For each integer in this list:
The hundreds digit represents the depth D of this node, 1 <= D <= 4.
The tens digit represents the position P of this node in the level it belongs to, 1 <= P <= 8. The position is the same as that in a full binary tree.
The units digit represents the value V of this node, 0 <= V <= 9.
Given a list of ascending three-digits integers representing a binary with the depth smaller than 5. You need to return the sum of all paths from the root towards the leaves.

Example 1:
Input: [113, 215, 221]
Output: 12
Explanation:
The tree that the list represents is:
3
/ \
5 1

The path sum is (3 + 5) + (3 + 1) = 12.
Example 2:
Input: [113, 221]
Output: 4
Explanation:
The tree that the list represents is:
3
\
1

The path sum is (3 + 1) = 4.

思路分析

本题并不难,一个简单的层序遍历。如果是固守之前解层序遍历的通用方法,一个直接的解法就是利用层序关系先构建完整的树,然后再对树进行先序遍历得到结果。但事实上,层序遍历本身已经访问了所有的元素,构建树的本身就是多余操作。我们先构建一个矩阵,把所有的数进行解析,然后对这个矩阵进行层序遍历,即可得到结果。代码如下:

class Solution {public:    int totalSum = 0;    int pathSum(vector<int>& nums) {        if(nums.empty())return 0;        int depth = nums.back()/100;        vector<vector<int>> matrix(depth,vector<int>(pow(2,depth),-1));        for(int i = 0;i<nums.size();++i) {            int d = nums[i]/100;            int pos = (nums[i]%100)/10;            int value = nums[i]%10;            matrix[d-1][pos-1] = value;        }        calculate(matrix,0,0,matrix[0][0]);        return totalSum;    }    void calculate(vector<vector<int>>& matrix,int level, int node,int sum) {        if(level+1==matrix.size()) {            totalSum+=sum;            return;          }         if(matrix[level+1][2*node]==-1&&matrix[level+1][2*node+1]==-1) {            // over             totalSum+= sum;            return;        }        if(matrix[level+1][2*node] != -1) {            calculate(matrix,level+1,node*2,sum+matrix[level+1][2*node]);        }         if(matrix[level+1][2*node+1]!=-1) {            calculate(matrix,level+1,node*2+1,sum+matrix[level+1][2*node+1]);        }     }};