leetcode 666. Path Sum IV

56 篇文章 0 订阅
53 篇文章 0 订阅

写在前面

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]);
        }
     }


};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值