3ms recursive java solution with rotation


  • 1
    K
      public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        permute(nums, 0, result);
        return result;
      }
    
      private void permute(int[] arr, int cursor, List<List<Integer>> result) {
        int len = arr.length - cursor;
        if (len == 1) {
          List<Integer> lst = new ArrayList<>();
          for (int i : arr) {
            lst.add(i);
          }
          result.add(lst);
        } else {
          for (int i = cursor; i < arr.length; i++) {
            rotate(arr, i, cursor);
            permute(arr, cursor + 1, result);
            rotate(arr, i, cursor);
          }
        }
      }
    
      private void rotate(int[] arr, int x, int y) {
        int tmp = arr[x];
        arr[x] = arr[y];
        arr[y] = tmp;
      }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.