46 Permutations 全排列

Given a collection of distinct(不同) integers, return all possible permutations(全排列).

Example:

 Input: [1,2,3]
 Output:
 [
     [1,2,3],
     [1,3,2],
     [2,1,3],
     [2,3,1],
     [3,1,2],
     [3,2,1]
 ]

这道题跟这道题https://github.com/longpf/AtOffer#27-字符串的排列简直一模一样

 vector<vector<int>> permute(vector<int>& nums) {
    vector<vector<int>> res{};
    if (nums.size() == 0) return res;
    permuteCore(res, nums, 0, nums.size());
    return res;
}
    
void permuteCore(vector<vector<int>> &res,vector<int> &num,int k,int n){
    if (k == n) {
        res.push_back(num);
        return;
    }
    for (int i = k; i<n; i++) {
        swap(num[i], num[k]);
        permuteCore(res, num, k+1, n);
        swap(num[i], num[k]);
    }
}
 
comments powered by Disqus