【leetcode】339. Nested List Weight Sum

原题

Given a nested list of integers, return the sum of all integers in the list weighted by their depth.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1:
Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1)

Example 2:
Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 42 + 63 = 27)

解析

嵌套数组加权和
给出一个数组,该数组的元素可能是一个数字,也可能是一个数组
最外层数组权重是1,向内一层权重+1,
求给出数组的权重和

解题思路

递归求和,第一层权重为1,判断该元素是int还是数组;若是数组,直接数字乘以权重;若是数组,递归调用方法,权重+1

我的解法

因为没有现成的数据结构,所以需要自己定义一个

/**
 * 自定义嵌套数组
 * Created by Administrator on 2017/7/19.
 */
public class NestedInteger {
    //包含一个整数
    private Integer integer;
    //以及一个数组
    private List<NestedInteger> nestedIntegers;

    //初始化Int
    public NestedInteger(Integer integer) {
        this.integer = integer;
    }

    //初始化数组
    public NestedInteger(List<NestedInteger> nestedIntegers) {
        this.nestedIntegers = nestedIntegers;
    }

    //判断是否int
    public Boolean isInteger() {
        if (integer != null && nestedIntegers == null) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    //判断是否数组
    public Boolean isNestedIntger() {
        if (integer == null && nestedIntegers != null) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    //Getter Setter
    public Integer getInteger() {
        return integer;
    }

    public void setInteger(Integer integer) {
        this.integer = integer;
        this.nestedIntegers = null;
    }

    public List<NestedInteger> getNestedIntegers() {
        return nestedIntegers;
    }

    public void setNestedIntegers(List<NestedInteger> nestedIntegers) {
        this.nestedIntegers = nestedIntegers;
        this.integer = null;
    }
}

然后再递归实现求和

/**
 * 339. Nested List Weight Sum
 * 嵌套数组加权和
 */
public class NestedListWeightSum {
    public static int getWeightSum(List<NestedInteger> nestedIntegers, int weight) {
        if (nestedIntegers == null || nestedIntegers.size() <= 0 || weight <= 0) {
            return 0;
        }
        int weightSum = 0;
        for (int i = 0; i < nestedIntegers.size(); i++) {
            if (nestedIntegers.get(i) != null && nestedIntegers.get(i).isInteger()) {
                weightSum += nestedIntegers.get(i).getInteger() * weight;
            } else {
                weightSum += getWeightSum(nestedIntegers.get(i).getNestedIntegers(), weight + 1);
            }
        }
        return weightSum;
    }
}
posted @ 2017-07-19 07:48  l.shane  阅读(168)  评论(0编辑  收藏  举报