Leetcode 46. Permutations

题目链接
问题描述

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

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
解题思路

这是求一个数组的全排列。使用DFS的方法,用path向量记录每一种排列,并将path存储到ret中。每次将nums中元素push到path前都要检查该元素是否已经在path中存在,可以通过将nums元素的index存入pickIndex向量进行记录来解决这个问题。代码如下:

class Solution {
public:
	vector<vector<int>> permute(vector<int>& nums) {
		vector<vector<int> > ret;
		vector<int> order;
		vector<int> pickIndex;
		if (nums.size() == 0) return ret;
		helper(nums, 0, pickIndex, order, ret);
		return ret;
	}
	void helper(vector<int>& nums, int nowIndex, vector<int>& pickIndex, vector<int>& order, vector<vector<int> >& ret) {
		if (pickIndex.size() == nums.size()) {
			ret.push_back(order);
			return;
		}
		vector<int>::iterator it;
		for (int i = 0; i < nums.size(); i++) {
			it = find(pickIndex.begin(), pickIndex.end(), i);
			if (it != pickIndex.end()) continue;
			pickIndex.push_back(i);
			order.push_back(nums[i]);
			helper(nums, nowIndex, pickIndex, order, ret);
			pickIndex.pop_back();
			order.pop_back();
		}
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值