Generate a sequence of all permutation of some ran

2019-05-24 10:35发布

The following algorithm is given and we are supposed to write it out in java. However, when I try to understand line by line, it gets confusing, especially the part:

A[k+1:N-1] = the values in S in ascending order

To my understand, the set only have 1 number at anytime. How can we replace A[k+1:N-1] when the set only has 1 number?

Let A be a sequence of integers 0 to N-1 in ascending order (let's assume its an array of int[N]).

next_permutation(A):
    k = N-1
    S = { }
    while k >= 0:
        if S contains a value larger than A[k]:
            v = the smallest member of S that is larger than A[k]
            remove v from S
            insert A[k] in S
            A[k] = v
            A[k+1:N-1] = the values in S in ascending order.
            return true
        else:
            insert A[k] in S
            k -= 1
    return false

1条回答
ゆ 、 Hurt°
2楼-- · 2019-05-24 10:43

The algorithm shown is similar to the Generation in lexicographic order. You can read the article for further information.

@templatetypedef Any clue on how I can replace items in an array by values in a set in ascending order? e.g. A[k+1:N-1] = the values in S in ascending order. Should I use toArray()?

This is not needed. You can try to keep the S array sorted all the time. Every time you want to insert a new number in the array, you insert it in such, so the array could stay sorted. For example, if you have S = [5 7 8] so far and you want to insert 6, you inserted between 5 and 7 - S = [5 6 7 8]. This way the replacement step is just copying the elements from S to A[k+1:N-1].

查看更多
登录 后发表回答