Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permutation Leetcode

I was solving this leetcode permutation problem and came across an error that am getting n empty lists inside my returned list which suppose to print different permutations of the given list

getting output => [[], [], [], [], [], []]

Expected output=> [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

def permute(nums):
    l=[]
    s=list()
    ans=[]

        return helper(nums,s,l)
def helper(nums,s,l):
    if not nums:
        print(l)
        s.append(l)
    else:
        for i in range(len(nums)):
            c=nums[i]
            l.append(c)
            nums.pop(i)
            helper(nums,s,l)
            nums.insert(i,c)
            l.pop()
    return s
print(permute([1,2,3]))
like image 844
yolon bsn Avatar asked Sep 15 '19 20:09

yolon bsn


People also ask

What is permutation of an array?

A permutation is a rearrangement of members of a sequence into a new sequence. For example, there are 24 permutations of [a, b, c, d]. Some of them are [b, a, d, c], [d, a, b, c] and [a, d, b, c].

How do you calculate permutations?

The number of permutations of n objects taken r at a time is determined by the following formula: P(n,r)=n! (n−r)!

What is permutation coding?

Programming by permutation, sometimes called "programming by accident" or "shotgunning", is an approach to software development wherein a programming problem is solved by iteratively making small changes (permutations) and testing each change to see if it behaves as desired.

How do you generate all permutations of an array in C++?

We can generate all permutations of an array by making use of the STL function next_permutation. A call of next_permutation returns the next lexicographically smallest permutation. If the sequence is lexicographically largest, the function returns false.


1 Answers

You should do s.append(l.copy()) because otherwise you pop all values from the same list l, that's why the result consists of empty lists.

like image 140
sanyassh Avatar answered Oct 23 '22 15:10

sanyassh