#15 Permutations

题目描述:

Given a list of numbers, return all possible permutations.

 Notice

You can assume that there is no duplicate numbers in the list.

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]
]
题目思路:

这题我用了传统的recursion,每个recursion都遍历一遍array,找到没被访问过的element填入一个临时vector中。

Mycode(AC = 22ms):

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>> ans;
        if (nums.size() == 0) return ans;
        
        vector<int> sofar;
        unordered_set<int> visited;
        permute(ans, sofar, nums, visited);
        return ans;
    }
    
    void permute(vector<vector<int>>& ans,
                 vector<int>& sofar,
                 vector<int>& nums,
                 unordered_set<int>& visited)
    {
        if (sofar.size() == nums.size()) {
            ans.push_back(sofar);
            return;
        }
        
        for (int i = 0; i < nums.size(); i++) {
            if (visited.find(nums[i]) == visited.end()) {
                sofar.push_back(nums[i]);
                visited.insert(nums[i]);
                
                permute(ans, sofar, nums, visited);
                
                sofar.pop_back();
                visited.erase(nums[i]);
            }
        }
    }
};


阅读更多
版权声明:三千微尘里,吾宁爱与憎 https://blog.csdn.net/haifischxia/article/details/52368349
文章标签: lintcode recursion
个人分类: lintcode
上一篇#29 Interleaving String
下一篇#16 Permutations II
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭