zoukankan      html  css  js  c++  java
  • LeetCode Permutations

    链接: https://oj.leetcode.com/problems/permutations/


    每次从num中选择一个数添加到结果中,并用used标记用过的数.

    public class Solution {
    	private boolean used[];
    	private  List<List<Integer> > ans;
    	private  List<Integer> tans ;
    	public  List<List<Integer> > permute(int[] num)
    	{
    		used=new boolean[num.length];
    		ans=new ArrayList<List<Integer>>();
    		tans=new ArrayList<Integer>() ;
    		for(int i=0;i<used.length;i++)
    			used[i]=false;
    		my_next_permute(0,num.length,num);
    		return ans;
    	}
    	public void my_next_permute(int pos,int n,int[] num)
    	{
    		
    		if(pos==n)	
    		{
    			ans.add(new ArrayList<Integer>(tans));
    			
    			return ;
    		}
    		for(int i=0;i<n;i++)
    		{
    			if(!used[i])
    			{
    				tans.add(new Integer(num[i]));
    				used[i]=true;
    				my_next_permute(pos+1,n,num);
    				tans.remove(tans.size()-1);
    				used[i]=false;
    			}
    		}
    	return;
    	}
    };
    

    C++的STL中有next_permutation()函数,可以求出下一个全排列


    class Solution
    {
    	public:
    		vector<vector<int> > permute(vector<int> &num)
    		{
    			vector<vector<int> > ans;
    			sort(num.begin(),num.end());
    			ans.push_back(num);
    			while(next_permutation(num.begin(),num.end()))
    			{
    				ans.push_back(num);
    			}
    			return ans;
    
    		}
    };


  • 相关阅读:
    C# delegate委托的用法
    C# new关键字的使用
    C# abstract抽象类的使用
    C# override关键字的使用
    C# sealed关键字的使用
    C# 虚函数virtual的使用
    Java IO流简介
    SpringBoot中异步请求的使用
    SpringBoot中异步调用的使用
    github
  • 原文地址:https://www.cnblogs.com/frankM/p/4399451.html
Copyright © 2011-2022 走看看