无重复元素求全排列分递归和非递归版本
①递归版本
ABCD全排列 = A开头,BCD结尾的情况+B开头,ACD结尾的情况+C开头+D开头,就是第1个数跟后面的数交换
而A开头,BCD结尾的情况又可以递归处理,这时A已确定,对于BCD,再B分别和C、D交换...
当前数与后面的数交换得出全排列(下面代码是int的,可转为字符串)
C++版
void digui_next(int s1[],int cur,int n)
{
if(n==cur)
{
output(s1,n);
}
else
{
for(int i=cur;i<n;i++)
{
swap(s1[i],s1[cur]);
digui_next(s1,cur+1,n);
swap(s1[i],s1[cur]);
}
}
}
JAVA版:
https://leetcode.com/problems/permutations/
class N46_Solution {
//https://blog.csdn.net/u012469987/article/details/43090703
private List<List<Integer>> ans;
public List<List<Integer>> permute(int[] nums) {
ans = new ArrayList<>();
dfs(nums,0);
return ans;
}
public void dfs(int[] nums,int cur) {
if(cur == nums.length ){
List<Integer> tempList = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
tempList.add(nums[i]);
}
ans.add(tempList);
return;
}
for (int i = cur; i < nums.length; i++) {
swap(nums,i, cur );
dfs(nums,cur+1);
swap(nums,i, cur );
}
}
private void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
public class N46_permutations {
public static void main(String[] args) {
int[] nums = new int[]{1,2,3};
List<List<Integer>> list = new N46_Solution().permute(nums);
System.out.println(list);
}
}
②非递归版本
看这个,讲得实在不错 http://taop.marchtea.com/01.06.html
int fun(char *s1, int n) {
int i = n - 2;
while (i >= 0 && s1[i] >= s1[i + 1]) i--;
if (i < 0) return false;
int j = n - 1;
while (j > 0 && s1[j] < s1[i]) j--;
swap(s1[i], s1[j]);
reverse(s1 + i + 1, s1 + n);
return true;
}