LeetCode 47. Permutations II

Permutations II.

Exactly the same asĀ Permutations.

public class Solution {
    public IList<IList<int>> PermuteUnique(int[] nums) {
        IList<IList<int>> ret = new List<IList<int>>();
        Array.Sort(nums);
        ret.Add(new List<int>(nums));
        while(NextPermutation(nums)) ret.Add(new List<int>(nums));
        return ret;
    }
    
    public bool NextPermutation(int[] nums) {
        int pos1 = -1;
        for (int i = nums.Length-1; i > 0; i--){
            if(nums[i] > nums[i-1]) {
                pos1 = i-1;
                break;
            }
        }
        if (pos1 == -1){
            return false;
        }
        for (int i = nums.Length-1; i > 0; i--){
            if(nums[pos1] < nums[i]){
                int t = nums[pos1];
                nums[pos1] = nums[i];
                nums[i] = t;
                Array.Reverse(nums, pos1+1, nums.Length - pos1 - 1);
                break;
            }
        }
        return true;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *