首页 > 代码库 > Permutations

Permutations

Permutations

Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

分析: 全排列实现思想是从start开始,分别和后面的数进行交换,递归求解

class Solution {
public:
    void swap(int i, int j, vector<int>& nums){
        int temp =nums[i];
        nums[i] = nums[j];
        nums[j]= temp;
    }
    void allRange(int start, vector<int>& nums, vector<vector<int>>& res)
    {
        if(start==nums.size()-1)
            return;
        for(int i =start; i<nums.size(); i++){
            cout << start << " "<<i<<endl;
            swap(start, i, nums);
            if(start!=i)
                res.push_back(nums);
            allRange(start+1, nums, res);
            swap(i, start, nums);
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> res;
        if(nums.size()==0)
            return res;
        res.push_back(nums);
        allRange(0, nums, res);
        return res;
        
    }
};

  

 

Permutations