Leetcode 46/47 Permutations, Permutations II

今天做了Leetcode,还挑了一个比较简单的....Permutations

几个注意点:

1.用next permutation做

2.注意swap的时候的下标号

3.注意判断数组是否遍历完毕的时候(70行),判断依据是i<0,而不是i==0,想一想为什么?

(因为数组遍历完还没有找到条件,所以i已经超出了范围!)

4.如果给定的数组有重复元素,这种方法也是可以生成所有的排列的(所以permutaions II也可以过)。

5.72ms Judge Large for Question 46, 168ms Judge Large for Question 47



#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
//L46 Permutations
//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].


//next permutation method
//we have 123 next is 132 next is 213
//how to find the next permutation?
//we should modify the left as little as possible, so we search from the right.
//find the first element that is ai < a(i+1), that is, there exists one “next permutation”. if not, we are done
//find the smallest larger element than ai from right(ai+1 or the element in the right of it), say aj
//then we swap the ai and aj, so the new “integer” is larger.
//but we will find the “next” permutation, so we should make it smaller
//because currently, the ele in ai+1 is in descending order, so we make it as an ascending order. we just need a transposition.


//edge case: num is empty, or only have 1 element.
class Solution
{
public:
	void swap(int *a, int *b)
	{
		if (a == b)
			return;
		int temp;
		temp = *a;
		*a = *b;
		*b = temp;
	}
	vector<vector<int> > permute(vector<int> &num)
	{
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		vector<int> result;
		vector<vector<int> > ret;
		int len = num.size();
		if (num.empty())
			return ret;
		if (len == 1)
		{
			ret.push_back(num);
			return ret;
		}
		//sort for all the permutaions
		sort(num.begin(), num.end());
		int i, j;
		while (1)
		{
			//store the result
			ret.push_back(num);
			//we find ai < ai+1
			for (i = len - 2; i >= 0; i--)
				if (num[i] < num[i + 1])
					break;
			cout << num[0] << "  " << num[1] << " " << num[2] << endl;
			//check if there exists the next permutation
			if (i < 0 && num[0] >= num[1])
				break; //break the while loop, we are done.
			//find aj
			for (j = len - 1; j >= i + 1; j--)
				if (num[j] > num[i])
					break;
			//swap ai and aj
			swap(&num[i], &num[j]);
			//transposition from ai+1 to the end
			int k;
			for (k = i + 1; k <= (i + 1 + (len - 1 - (i + 1)) / 2); k++)
				swap(&num[k], &num[len - k + i]);


		}
		return ret;
	}
};


int main()
{
	Solution S;
	vector<int> arr;
	arr.push_back(1);
	arr.push_back(2);
	arr.push_back(3);
	S.permute(arr);
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值