全排列【回溯实现】

其他的就是全排列的操作,用的是回溯的方法进行操作

知识点:

1、填充进一个需要得到的列表(容器)中的时候需要首先应用拷贝到指定的位置才行。

eg。res.add(new ArrayList<Integer>(output));

2、Connection.swap(List,int,int);  交换List中位置是两个数字值的位置。

3、List是个接口,ArrayList是实现类,如果想要使用List需要使用List变量同时new ArrayList()才行。在另外的函数声明中变量类型还是List。具体的区别还得看看其他博客。

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();

        List<Integer> output = new ArrayList<Integer>();
        for (int num : nums) {
            output.add(num);
        }

        int n = nums.length;
        backtrack(n, output, res, 0);
        return res;
    }

    public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
        // 所有数都填完了
        if (first == n) {
            res.add(new ArrayList<Integer>(output));
        }
        for (int i = first; i < n; i++) {
            // 动态维护数组
            Collections.swap(output, first, i);
            // 继续递归填下一个数
            backtrack(n, output, res, first + 1);
            // 撤销操作
            Collections.swap(output, first, i);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
全排列是指将一组数按照不同的顺序排列,共有n!种排列方式,其中n为数的个数。回溯算法是一种基于搜索的算法,它试图通过不断地搜索所有可能的解,直到找到一个符合要求的解为止。 以下是用C语言实现全排列回溯算法: ```c #include<stdio.h> #include<stdlib.h> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void permute(int *array, int start, int end) { if (start == end) { for (int i = 0; i <= end; i++) { printf("%d ", array[i]); } printf("\n"); } else { for (int i = start; i <= end; i++) { swap(&array[start], &array[i]); permute(array, start+1, end); swap(&array[start], &array[i]); } } } int main() { int array[3] = {1, 2, 3}; permute(array, 0, 2); return 0; } ``` 在上面的代码中,swap函数用于交换两个数的值,permute函数用于递归实现全排列。当start等于end时,表示找到了一种排列方式,将其输出即可。否则,通过交换数组中的元素,不断地递归调用permute函数,直到找到所有的排列方式为止。 具体实现中,我们从数组的第一个元素开始,将其与后面的元素交换,然后递归调用permute函数,再将元素交换回来,接着换第二个元素,第三个元素,直到最后一个元素。这样就可以得到所有的排列方式。 例如,对于数组{1, 2, 3},通过上述算法可以得到以下6种排列方式: 1 2 3 1 3 2 2 1 3 2 3 1 3 2 1 3 1 2 这就是用C语言实现全排列回溯算法

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值