图片.png
    接着上一个组合问题,这是个排列问题,就是先后顺序了

    1. class Solution {
    2. public List<List<Integer>> permute(int[] nums) {
    3. List<List<Integer>> res = new ArrayList<List<Integer>>();
    4. List<Integer> output = new ArrayList<Integer>();
    5. for (int num : nums) {
    6. output.add(num);
    7. }
    8. int n = nums.length;
    9. backtrack(n, output, res, 0);
    10. return res;
    11. }
    12. public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
    13. // 所有数都填完了
    14. if (first == n) {
    15. res.add(new ArrayList<Integer>(output));
    16. }
    17. for (int i = first; i < n; i++) {
    18. // 动态维护数组
    19. Collections.swap(output, first, i);
    20. // 继续递归填下一个数
    21. backtrack(n, output, res, first + 1);
    22. // 撤销操作
    23. Collections.swap(output, first, i);
    24. }
    25. }
    26. }