Leetcode 46 Permutations

2018-01-12 15:06:46 浏览数 (1)

Given a collection of distinct numbers, return all possible permutations.

For example, [1,2,3] have the following permutations:

代码语言:javascript复制
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

找出全排列。

直接用next_permutation实现

代码语言:javascript复制
class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> result;
        sort(nums.begin(),nums.end());
        do
        {
            result.push_back(nums);
        }while(next_permutation(nums.begin(),nums.end()));
        return result;
    }
};

DFS实现

代码语言:javascript复制
class Solution {
public:
    void dfs(vector<vector<int>> &result,vector<int> nums,vector<int> now)
    {
        if(nums.size() == 0)
        {
            result.push_back(now);
            return ;
        }
        for(int i=0;i<nums.size();i  )
        {
            now.push_back(nums[i]);
            vector<int> temp=nums;
            temp.erase(temp.begin() i);
            dfs(result,temp,now);
            now.pop_back();
        }
    }
    vector<vector<int>> permute(vector<int>& nums) 
    {
        vector<vector<int>> result;
        vector<int> now;
        dfs(result,nums,now);
        return result;
    }
};

0 人点赞