LeetCode:Permutations

Given a collection of 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].

// Source : https://oj.leetcode.com/problems/permutations/
// Author : Chao Zeng
// Date   : 2014-12-26

class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) {
        vector<vector<int> > tmp;
        dfs (tmp,num,0);
        return tmp;
    }

    void dfs(vector<vector<int> > &tmp, vector<int> &num, int cur){
        if (num.size() == cur){
            tmp.push_back(num);
        }
        else{
            for (int i = cur; i < num.size(); i++){
                swap(num[cur],num[i]);
                dfs(tmp,num,cur+1);
                swap(num[cur],num[i]);
            }
        }
    }
};


你可能感兴趣的:(LeetCode,递归)