permutations (dfs递归)

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]
]
class Solution {
public:
    vector> permute(vector& nums) {
        /*  1 2 3 4 5
         *  利用dfs 遍历到的长度 等于数组长度时记录当前结果
         *   关键在于当前结果怎么产生
         *   一种做法是: 交换 后进行dfs
         *   即 每次进行所有可能的交换
         * */
        vector> ret;

        dfs(nums, nums.size(), 0, ret);
        return ret;
    }
    void dfs(vector &nums, int size, int index, vector> &ret){
        // index == size 代表已经搜索到一条完整的路径
        if(index == size)   ret.push_back(nums);
        else{
            for(int i=index;i

 

你可能感兴趣的:(leetcode)