ris*_*hat 18
这里描述了一个很好的解决方案:https://www.nayuki.io/page/next-lexicographical-permutation-algorithm.并且,如果存在下一个排列,则返回它的解决方案,否则返回false:
function nextPermutation(array) {
var i = array.length - 1;
while (i > 0 && array[i - 1] >= array[i]) {
i--;
}
if (i <= 0) {
return false;
}
var j = array.length - 1;
while (array[j] <= array[i - 1]) {
j--;
}
var temp = array[i - 1];
array[i - 1] = array[j];
array[j] = temp;
j = array.length - 1;
while (i < j) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
return array;
}
Run Code Online (Sandbox Code Playgroud)
Hel*_*rld 14
使用@Fleischpfanzerl 引用的来源
我们按照以下步骤找到下一个字典排列:
nums = [0,1,2,5,3,3,0]
nums = [0]*5
curr = nums[-1]
pivot = -1
for items in nums[-2::-1]:
if items >= curr:
pivot -= 1
curr = items
else:
break
if pivot == - len(nums):
print('break') # The input is already the last possible permutation
j = len(nums) - 1
while nums[j] <= nums[pivot - 1]:
j -= 1
nums[j], nums[pivot - 1] = nums[pivot - 1], nums[j]
nums[pivot:] = nums[pivot:][::-1]
> [1, 3, 0, 2, 3, 5]
Run Code Online (Sandbox Code Playgroud)
所以这个想法是:这个想法是按照步骤 -
在家工作?反正可以看看C++函数std::next_permutation,或者这个:
http://blog.bjrn.se/2008/04/lexicographic-permutations-using.html