46 Permutations

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
函数   next_permutation()
/**
 *
 * @author dongb
 * Permutations
 * rebuild next_purmation()
 * TC O(n!), SC O(1)
 */
public class Solution {
    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        
        do {
            ArrayList<Integer> first = new ArrayList<>();
            for (int i: nums) {
                first.add(i);
            }
            result.add(first);
        } while (nextPermutation(nums, 0, nums.length));
        
        return result;
    }
    
    private static boolean nextPermutation(int[] nums, int begin, int end) {
        // From right to left, find the first digit(partitionNumber) 
        // which violates the increase trend
        int p = end - 2;
        while (p > -1 && nums[p] >= nums[p + 1]) --p;

        // If not found, which means current sequence is already the largest
        // permutation, then rearrange to the first permutation and return false
        if(p == -1) {
            reverse(nums, begin, end);
            return false;
        }

        // From right to left, find the first digit which is greater
        // than the partition number, call it changeNumber
        int c = end - 1;
        while (c > 0 && nums[c] <= nums[p]) --c;

        // Swap the partitionNumber and changeNumber
        swap(nums, p, c);
        // Reverse all the digits on the right of partitionNumber
        reverse(nums, p+1, end);
        return true;
    }
    private static void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    private static void reverse(int[] nums, int begin, int end) {
        end--;
        while (begin < end) {
            swap(nums, begin++, end--);
        }
    }
    
    public static void main(String args[]) {
        Scanner cin = new Scanner(System.in);
        int[] nums = new int[3];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = cin.nextInt();
        }
        List<List<Integer>> answer = permute(nums);
        System.out.println(answer);
    }
}


本题是求路径本身,求所有解,函数参数需要标记当前走到了哪步,还需要中间结   果的引用,最终结果的引用。扩展节点,每次从左到右,选一个没有出现过的元素。本题不需要判重,因为状态装换图是一颗有层次的树。收敛条件是当前走到了最后  一个元素

/**
 *
 * @author dongb
 * Permutations
 * Recursion, DSF, incremental construction
 * TC O(n!), SC O(n)
 */
public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        Arrays.sort(nums);
        
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        boolean[] selected = new boolean[nums.length];
        dfs(nums, selected, path, result);
        return result;
    }
    
    private void dfs(int[] nums, boolean[] selected, List<Integer> path, List<List<Integer>> result) {
        if (path.size() == nums.length) {   // convergence condition
            result.add(new ArrayList<Integer>(path));
            return;
        }
        
        // expand condition
        for (int i = 0; i < nums.length; i++) {
            if (selected[i]) {
                continue;
            }
            
            selected[i] = true;
            path.add(nums[i]);
            dfs(nums, selected, path, result);
            selected[i] = false;
            path.remove(path.size() - 1);
        }
    }
}

### C++ 实现全排列算法示例 #### 使用回溯法实现全排列 为了生成给定数组 `nums` 的所有可能排列,可以采用回溯方法。这种方法通过逐步构建候选解并撤销选择来进行探索。 ```cpp #include <vector> using namespace std; void backtrack(vector<int>& nums, vector<vector<int>>& result, int start) { if (start == nums.size()) { result.push_back(nums); return; } for (int i = start; i < nums.size(); ++i) { swap(nums[start], nums[i]); backtrack(nums, result, start + 1); // 继续处理下一个位置 swap(nums[start], nums[i]); // 恢复原状以便尝试其他可能性 } } vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> result; if (nums.empty()) return result; backtrack(nums, result, 0); return result; } ``` 这段代码展示了如何利用递归来遍历每一个元素作为起始点,并交换当前索引与其他未使用的数值的位置,从而形成新的组合[^1]。 #### 利用标准库函数 `next_permutation` 除了手动编写回溯逻辑外,还可以借助 STL 提供的功能简化开发过程: ```cpp #include <algorithm> #include <vector> vector<vector<int>> permuteSTL(const vector<int>& nums) { vector<vector<int>> permutations; vector<int> temp = nums; sort(temp.begin(), temp.end()); do { permutations.push_back(temp); } while (std::next_permutation(temp.begin(), temp.end())); return permutations; } ``` 此版本先对输入序列进行了排序操作,之后调用了内置的 `next_permutation()` 函数迭代获取所有的排列情况[^4]。 #### 基于协程的全排列方案 对于更复杂的场景或者追求性能优化的情况下,也可以考虑使用协程来并发执行多个子任务以提高效率: ```cpp // 这里仅提供概念性的伪代码框架,具体实现依赖编译器支持程度以及平台特性 generator<vector<int>> coroutinePermute(vector<int> remainingElements){ if(remainingElements.empty()){ co_return; } for(auto& elem : remainingElements){ auto currentElement = elem; auto restOfList = remove_element_from_list(currentElement); yield {currentElement}; for(auto subsequence : coroutinePermute(restOfList)){ yield prepend_to_sequence(subsequence, currentElement); } } } ``` 上述片段展示了一个基于协程的概念模型,在实际应用中需根据目标环境调整语法细节[^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值