[leetcode] Permutations

来源:互联网 发布:上瘾网络剧见面会视频 编辑:程序博客网 时间:2024/04/30 23:06

Permutations 


Total Accepted: 5072 Total Submissions: 16450

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].


参考

http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/

class Solution {
public:
    void dfs(vector<int> &num, int step, vector<vector<int> > &res) {
        if (step > num.size()-1) {
            res.push_back(num);
            return;
        }
        int i;
        for (i = step; i < num.size(); i++) {
            swap(num[i], num[step]);
            dfs(num, step + 1, res);   // 注意别写成step++了。。。 回溯回不来了。。
            swap(num[i], num[step]);
        }
    }
    vector<vector<int> > permute(vector<int> &num) {
        vector<vector<int> > res;
        dfs(num, 0, res);
        return res;
    }
};

0 0
原创粉丝点击