[Leetcode] Nested list Weight Sum II nested list weights and two

Source: Internet
Author: User

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

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

Different from the previous question where weight are increasing from root to leaf, now the weight are defined from bottom u P. i.e., the leaf level integers has weight 1, and the root level integers has the largest weight.

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

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

The problem is the extension of the previous nested List Weight sum, and the difference is that the deeper the problem, the smaller the weight, and the exact opposite. But the problem-solving mentality has not changed, you can also use DFS to do, then because of the traversal of the end of the depth do not know how deep, you can not traverse the time to directly accumulate the results, my first idea is to build a two-dimensional array in the process of traversal, the number of each layer is saved, and then finally know the depth, To calculate the weights and, for example, the two examples given in the topic, two-dimensional arrays are created:

[[1,1],2,[1,1]]:

1 1 1 1
2

[1,[4,[6]]:

1
4
6

So we can figure out the weights and see the code as follows:

Solution One:

classSolution { Public:    intDepthsuminverse (vector<nestedinteger>&nestedlist) {        intres =0; Vector<vector<int>>v;  for(auto a:nestedlist) {Helper (A,0, V); }         for(inti = v.size ()-1; I >=0; --i) { for(intj =0; J < V[i].size (); ++j) {Res+ = v[i][j] * (V.size ()-i); }        }        returnRes; }    voidHelper (Nestedinteger &ni,intDepth, vector<vector<int>> &v) {vector<int>T; if(Depth < V.size ()) T =V[depth]; ElseV.push_back (t); if(Ni.isinteger ()) {T.push_back (Ni.getinteger ()); if(Depth < V.size ()) v[depth] =T; ElseV.push_back (t); } Else {             for(Auto A:ni.getlist ()) {Helper (A, depth+1, V); }        }    }};

In fact, the above method can be simplified, because each layer of the number is not saved separately, each number is multiplied by the depth and then added, with each layer of the number first added up and then multiplied by the depth is the same, so we only need a one-dimensional array can be, as long as the number of each layer and save, and then calculate the weight and

Solution Two:

classSolution { Public:    intDepthsuminverse (vector<nestedinteger>&nestedlist) {        intres =0; Vector<int>v;  for(auto a:nestedlist) {Helper (A,0, V); }         for(inti = v.size ()-1; I >=0; --i) {res+ = v[i] * (V.size ()-i); }        returnRes; }    voidHelper (Nestedinteger ni,intDepth, vector<int> &v) {if(Depth >= v.size ()) v.resize (depth +1); if(Ni.isinteger ()) {v[depth]+=Ni.getinteger (); } Else {             for(Auto A:ni.getlist ()) {Helper (A, depth+1, V); }        }    }};

The following method is more ingenious, by Stephen The Great God, this method used two variables unweighted and weighted, non-weights and weights and, initialization is 0, and then if nestedlist not empty start loop, First declare an empty array nextlevel, traverse the elements in the nestedlist , if it is a number, then non-weighted and add this number, if it is an array, add nextlevel, so that after the completion of the traversal, The number of the first layer and stored in the non-weight and unweighted, the rest of the elements are deposited in the nextlevel, at this time we will add unweighted to weighted, nextlevel to nestedlist, so then into the next layer of calculation, Because the value of the previous layer is still in the unweighted, so the second layer after the calculation will unweighted join the weighted, the equivalent of the first layer of the number and was added two times, so that the perfect meet the requirements, this idea is clever and bull B, the great God is the great God, see the code as follows:

Solution Three:

classSolution { Public:    intDepthsuminverse (vector<nestedinteger>&nestedlist) {        intunweighted =0, weighted =0;  while(!Nestedlist.empty ()) {Vector<NestedInteger>Nextlevel;  for(Auto a:nestedlist) {if(A.isinteger ()) {unweighted+=A.getinteger (); } Else{Nextlevel.insert (Nextlevel.end (), a.getlist (). Begin (), A.getlist (). end ()); }} Weighted+=unweighted; Nestedlist=Nextlevel; }        returnweighted; }}; 

The following algorithm is the conventional BFS solution, using the above to build two variables unweighted and weighted ideas, basically no difference:

Solution Four:

classSolution { Public:    intDepthsuminverse (vector<nestedinteger>&nestedlist) {        intunweighted =0, weighted =0; Queue<vector<NestedInteger>>Q;        Q.push (nestedlist);  while(!Q.empty ()) {            intSize =q.size ();  for(inti =0; i < size; ++i) {vector<NestedInteger> T =Q.front (); Q.pop ();  for(Auto a:t) {if(A.isinteger ()) unweighted + =A.getinteger (); ElseQ.push (A.getlist ()); }} Weighted+=unweighted; }        returnweighted; }};

Similar topics:

Nested List Weight Sum

Resources:

Https://leetcode.com/discuss/110000/4ms-one-pass-dfs-c-solution

Https://leetcode.com/discuss/110075/no-depth-variable-no-multiplication

Https://leetcode.com/discuss/110097/standard-rewriting-stefanpochmanns-extra-interpretation

Leetcode all in one topic summary (continuous update ...)

[Leetcode] Nested list Weight Sum II nested list weights and two

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.