LeetCode: 46. Permutations
题目描述
Given a collection of distinct 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],
  [3,2,1]
]  题目大意就是让我们把给定数组的所有数字全排列列举出来。
解题思路
直接暴力搜索就 OK。
AC代码
class Solution {
public:
    void permute(vector<vector<int>>& ans, vector<int>& nums, vector<int>& now)
    {
        if(now.size() == nums.size())
        {
            ans.push_back(now);
            return;
        }
        for(int i = 0; i < nums.size(); ++i)
        {
            if(nums[i] != INT_MAX)
            {
                // 用过的数字标记为INT_MAX
                now.push_back(nums[i]);
                nums[i] = INT_MAX;
                permute(ans, nums, now);
                // 取消标记
                nums[i] = now.back();
                now.pop_back();
            }
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> ans;
        vector<int> now;
        permute(ans, nums, now);
        return ans;
    }
};
京公网安备 11010502036488号