46. 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], and [3,2,1].

回溯

采用交换元素的方法,元素 1 依次和元素 n ( n > 1 ) 交换
同理,元素 2 依次和元素 n ( n > 2 ) 交换
这样元素 2 就不会选到已经被确定的 元素 1
接下来,元素 k 依次和元素 n ( n > k ) 交换 ......

class Solution {
public:
    vector<vector<int>> result;

    vector<vector<int>> permute(vector<int>& nums) {
        backtrack(nums, 0);
        return result;
    }
    
    void backtrack(vector<int>& nums, int n){
        if(n == nums.size() - 1){
            result.push_back(nums);
        }
        //只和后面的交换
        for(int i = n; i < nums.size(); i++){
            swap(nums[n], nums[i]);
            backtrack(nums, n + 1);
            swap(nums[n], nums[i]);
        }
    }
};

你可能感兴趣的:(46. Permutations)