📌  相关文章
📜  使用回溯打印没有重复的数组/向量的所有可能排列

📅  最后修改于: 2022-05-13 01:56:06.641000             🧑  作者: Mango

使用回溯打印没有重复的数组/向量的所有可能排列

给定向量nums ,任务是使用回溯打印给定向量的所有可能排列

例子

方法:任务可以在回溯的帮助下解决。为了更好地理解,这里有一篇类似的文章:打印给定字符串的所有排列

下面是上述代码的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function for swapping two numbers
void swap(int& x, int& y)
{
    int temp = x;
    x = y;
    y = temp;
}
 
// Function to find the possible
// permutations
void permutations(vector >& res,
                  vector nums, int l, int h)
{
    // Base case
    // Add the vector to result and return
    if (l == h) {
        res.push_back(nums);
        return;
    }
 
    // Permutations made
    for (int i = l; i <= h; i++) {
 
        // Swapping
        swap(nums[l], nums[i]);
 
        // Calling permutations for
        // next greater value of l
        permutations(res, nums, l + 1, h);
 
        // Backtracking
        swap(nums[l], nums[i]);
    }
}
 
// Function to get the permutations
vector > permute(vector& nums)
{
    // Declaring result variable
    vector > res;
    int x = nums.size() - 1;
 
    // Calling permutations for the first
    // time by passing l
    // as 0 and h = nums.size()-1
    permutations(res, nums, 0, x);
    return res;
}
 
// Driver Code
int main()
{
    vector nums = { 1, 2, 3 };
    vector > res = permute(nums);
 
    // printing result
    for (auto x : res) {
        for (auto y : x) {
            cout << y << " ";
        }
        cout << endl;
    }
 
    return 0;
}


Python3
# Python program for the above approach
 
# Function to find the possible
# permutations
def permutations(res, nums, l, h) :
     
    # Base case
    # Add the vector to result and return
    if (l == h) :
        res.append(nums);
        for i in range(len(nums)):
            print(nums[i], end=' ');
 
        print('')
        return;
 
    # Permutations made
    for i in range(l, h + 1):
         
        # Swapping
        temp = nums[l];
        nums[l] = nums[i];
        nums[i] = temp;
 
        # Calling permutations for
        # next greater value of l
        permutations(res, nums, l + 1, h);
 
        # Backtracking
        temp = nums[l];
        nums[l] = nums[i];
        nums[i] = temp;
 
# Function to get the permutations
def permute(nums):
     
    # Declaring result variable
    x = len(nums) - 1;
    res = [];
     
    # Calling permutations for the first
    # time by passing l
    # as 0 and h = nums.size()-1
    permutations(res, nums, 0, x);
    return res;
 
# Driver Code
nums = [ 1, 2, 3 ];
res = permute(nums);
 
# This code is contributed by Saurabh Jaiswal


Javascript


输出
1 2 3 
1 3 2 
2 1 3 
2 3 1 
3 2 1 
3 1 2 

时间复杂度 O(N*N!) 注意有 N!排列,它需要 O(N) 时间来打印排列。
辅助空间 O(r – l)