码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Permutations

时间:2015-05-22 23:55:47      阅读:604      评论:0      收藏:0      [点我收藏+]

标签:

http://www.lintcode.com/en/problem/permutations/#

Given a list of numbers, return all possible permutations.

Example

For nums = [1,2,3], the permutations are:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
class Solution {
public:
    /**
     * @param nums: A list of integers.
     * @return: A list of permutations.
     */
    vector<vector<int> > permute(vector<int> nums) {
        // write your code here
        vector<vector<int>> paths;
        if (nums.empty()) {
            return paths;
        }
        
        vector<int> index;
        vector<int> path;
        permuteHelper(nums, index, path, paths);
        return paths;
        
    }
    
private:
    void permuteHelper(const vector<int> &nums,
                       vector<int> &index,    
                       vector<int> &path,
                       vector<vector<int>> &paths) {
        if (path.size() == nums.size()) {
            paths.push_back(path);
            return;
        }
        
        for (int ix = 0; ix < nums.size(); ix++) {
            if (find(index.begin(), index.end(), ix) == index.end()) {
                index.push_back(ix);
                path.push_back(nums[ix]);
                permuteHelper(nums, index, path, paths);
                index.pop_back();
                path.pop_back();
            }
        }                   
    }
};

[LintCode] Permutations

标签:

原文地址:http://www.cnblogs.com/jianxinzhou/p/4523416.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!