【题目】
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]
.
【题意】
给定一个数组,生成所有的全排列
【思路】
递归,类DFS
【代码】
class Solution { public: void dfs(vector<vector<int> >&result, vector<int>combination, vector<int>candidates, int index2remove){ //combination——当前已生成的组合 //candidates——候选数字集合 //index2remove——添加到combination的下一个数字在candidates中的索引位 combination.push_back(candidates[index2remove]); candidates.erase(candidates.begin()+index2remove); if(candidates.empty()){ result.push_back(combination); } else{ for(int i=0; i<candidates.size(); i++){ dfs(result, combination, candidates, i); } } } vector<vector<int> > permute(vector<int> &num) { vector<vector<int> >result; int size=num.size(); if(size==0)return result; vector<int> combination; for(int i=0; i<num.size(); i++){ dfs(result, combination, num, i); } return result; } };
LeetCode: Permutations [045],布布扣,bubuko.com
时间: 2024-10-22 01:05:28